MDL-11282 Just displaying a simple notice, and continuing with the regrading.
[moodle-pu.git] / question / type / questiontype.php
blob4859b4a429a8a040a31b09625ae7ee59ab24ab21
1 <?php // $Id$
2 /**
3 * The default questiontype class.
5 * @author Martin Dougiamas and many others. This has recently been completely
6 * rewritten by Alex Smith, Julian Sedding and Gustav Delius as part of
7 * the Serving Mathematics project
8 * {@link http://maths.york.ac.uk/serving_maths}
9 * @license http://www.gnu.org/copyleft/gpl.html GNU Public License
10 * @package questionbank
11 * @subpackage questiontypes
14 require_once($CFG->libdir . '/questionlib.php');
16 /**
17 * This is the base class for Moodle question types.
19 * There are detailed comments on each method, explaining what the method is
20 * for, and the circumstances under which you might need to override it.
22 * Note: the questiontype API should NOT be considered stable yet. Very few
23 * question tyeps have been produced yet, so we do not yet know all the places
24 * where the current API is insufficient. I would rather learn from the
25 * experiences of the first few question type implementors, and improve the
26 * interface to meet their needs, rather the freeze the API prematurely and
27 * condem everyone to working round a clunky interface for ever afterwards.
29 * @package questionbank
30 * @subpackage questiontypes
32 class default_questiontype {
34 /**
35 * Name of the question type
37 * The name returned should coincide with the name of the directory
38 * in which this questiontype is located
40 * @return string the name of this question type.
42 function name() {
43 return 'default';
46 /**
47 * The name this question should appear as in the create new question
48 * dropdown.
50 * @return mixed the desired string, or false to hide this question type in the menu.
52 function menu_name() {
53 $name = $this->name();
54 $menu_name = get_string($name, 'qtype_' . $name);
55 if ($menu_name[0] == '[') {
56 // Legacy behavior, if the string was not in the proper qtype_name
57 // language file, look it up in the quiz one.
58 $menu_name = get_string($name, 'quiz');
60 return $menu_name;
63 /**
64 * @return boolean true if this question can only be graded manually.
66 function is_manual_graded() {
67 return false;
70 /**
71 * @return boolean true if this question type can be used by the random question type.
73 function is_usable_by_random() {
74 return true;
77 /**
78 * @return whether the question_answers.answer field needs to have
79 * restore_decode_content_links_worker called on it.
81 function has_html_answers() {
82 return false;
85 /**
86 * If your question type has a table that extends the question table, and
87 * you want the base class to automatically save, backup and restore the extra fields,
88 * override this method to return an array wherer the first element is the table name,
89 * and the subsequent entries are the column names (apart from id and questionid).
91 * @return mixed array as above, or null to tell the base class to do nothing.
93 function extra_question_fields() {
94 return null;
97 /**
98 * If your question type has a table that extends the question_answers table,
99 * make this method return an array wherer the first element is the table name,
100 * and the subsequent entries are the column names (apart from id and answerid).
102 * @return mixed array as above, or null to tell the base class to do nothing.
104 function extra_answer_fields() {
105 return null;
109 * Return an instance of the question editing form definition. This looks for a
110 * class called edit_{$this->name()}_question_form in the file
111 * {$CFG->docroot}/question/type/{$this->name()}/edit_{$this->name()}_question_form.php
112 * and if it exists returns an instance of it.
114 * @param string $submiturl passed on to the constructor call.
115 * @return object an instance of the form definition, or null if one could not be found.
117 function create_editing_form($submiturl, $question, $category, $contexts, $formeditable) {
118 global $CFG;
119 require_once("{$CFG->dirroot}/question/type/edit_question_form.php");
120 $definition_file = $CFG->dirroot.'/question/type/'.$this->name().'/edit_'.$this->name().'_form.php';
121 if (!(is_readable($definition_file) && is_file($definition_file))) {
122 return null;
124 require_once($definition_file);
125 $classname = 'question_edit_'.$this->name().'_form';
126 if (!class_exists($classname)) {
127 return null;
129 return new $classname($submiturl, $question, $category, $contexts, $formeditable);
133 * @return string the full path of the folder this plugin's files live in.
135 function plugin_dir() {
136 global $CFG;
137 return $CFG->dirroot . '/question/type/' . $this->name();
141 * @return string the URL of the folder this plugin's files live in.
143 function plugin_baseurl() {
144 global $CFG;
145 return $CFG->wwwroot . '/question/type/' . $this->name();
149 * This method should be overriden if you want to include a special heading or some other
150 * html on a question editing page besides the question editing form.
152 * @param question_edit_form $mform a child of question_edit_form
153 * @param object $question
154 * @param string $wizardnow is '' for first page.
156 function display_question_editing_page(&$mform, $question, $wizardnow){
157 list($heading, $langmodule) = $this->get_heading(empty($question->id));
158 print_heading_with_help($heading, $this->name(), $langmodule);
159 $permissionstrs = array();
160 if (!empty($question->id)){
161 if ($question->formoptions->canedit){
162 $permissionstrs[] = get_string('permissionedit', 'question');
164 if ($question->formoptions->canmove){
165 $permissionstrs[] = get_string('permissionmove', 'question');
167 if ($question->formoptions->cansaveasnew){
168 $permissionstrs[] = get_string('permissionsaveasnew', 'question');
171 if (!$question->formoptions->movecontext && count($permissionstrs)){
172 print_heading(get_string('permissionto', 'question'), 'center', 3);
173 $html = '<ul>';
174 foreach ($permissionstrs as $permissionstr){
175 $html .= '<li>'.$permissionstr.'</li>';
177 $html .= '</ul>';
178 print_box($html, 'boxwidthnarrow boxaligncenter generalbox');
180 $mform->display();
184 * Method called by display_question_editing_page and by question.php to get heading for breadcrumbs.
186 * @return array a string heading and the langmodule in which it was found.
188 function get_heading($adding = false){
189 $name = $this->name();
190 $langmodule = 'qtype_' . $name;
191 if (!$adding){
192 $strtoget = 'editing' . $name;
193 } else {
194 $strtoget = 'adding' . $name;
196 $strheading = get_string($strtoget, $langmodule);
197 if ($strheading[0] == '[') {
198 // Legacy behavior, if the string was not in the proper qtype_name
199 // language file, look it up in the quiz one.
200 $langmodule = 'quiz';
201 $strheading = get_string($strtoget, $langmodule);
203 return array($strheading, $langmodule);
209 * @param $question
211 function set_default_options(&$question) {
215 * Saves or updates a question after editing by a teacher
217 * Given some question info and some data about the answers
218 * this function parses, organises and saves the question
219 * It is used by {@link question.php} when saving new data from
220 * a form, and also by {@link import.php} when importing questions
221 * This function in turn calls {@link save_question_options}
222 * to save question-type specific options
223 * @param object $question the question object which should be updated
224 * @param object $form the form submitted by the teacher
225 * @param object $course the course we are in
226 * @return object On success, return the new question object. On failure,
227 * return an object as follows. If the error object has an errors field,
228 * display that as an error message. Otherwise, the editing form will be
229 * redisplayed with validation errors, from validation_errors field, which
230 * is itself an object, shown next to the form fields.
232 function save_question($question, $form, $course) {
233 global $USER;
234 // This default implementation is suitable for most
235 // question types.
237 // First, save the basic question itself
238 $question->name = trim($form->name);
239 $question->questiontext = trim($form->questiontext);
240 $question->questiontextformat = $form->questiontextformat;
241 $question->parent = isset($form->parent)? $form->parent : 0;
242 $question->length = $this->actual_number_of_questions($question);
243 $question->penalty = isset($form->penalty) ? $form->penalty : 0;
245 if (empty($form->image)) {
246 $question->image = "";
247 } else {
248 $question->image = $form->image;
251 if (empty($form->generalfeedback)) {
252 $question->generalfeedback = '';
253 } else {
254 $question->generalfeedback = trim($form->generalfeedback);
257 if (empty($question->name)) {
258 $question->name = substr(strip_tags($question->questiontext), 0, 15);
259 if (empty($question->name)) {
260 $question->name = '-';
264 if ($question->penalty > 1 or $question->penalty < 0) {
265 $question->errors['penalty'] = get_string('invalidpenalty', 'quiz');
268 if (isset($form->defaultgrade)) {
269 $question->defaultgrade = $form->defaultgrade;
272 if (!empty($question->id)) { // Question already exists
273 if (isset($form->categorymoveto)){
274 question_require_capability_on($question, 'move');
275 list($question->categorymoveto, $movetocontextid) = explode(',', $form->categorymoveto);
276 //don't need to test add permission of category we are moving question to.
277 //Only categories that we have permission to add
278 //a question to will get through the form cleaning code for the select box.
279 if (isset($question->qtype) && $question->qtype != RANDOM){
280 $question->category = $question->categorymoveto;
283 // keep existing unique stamp code
284 $question->stamp = get_field('question', 'stamp', 'id', $question->id);
285 $question->modifiedby = $USER->id;
286 $question->timemodified = time();
287 if (!update_record('question', $question)) {
288 error('Could not update question!');
290 } else { // Question is a new one
291 // Set the unique code
292 list($question->category,$contextid) = explode(',', $form->category);
293 $question->stamp = make_unique_id_code();
294 $question->createdby = $USER->id;
295 $question->timecreated = time();
296 if (!$question->id = insert_record('question', $question)) {
297 error('Could not insert new question!');
301 // Now to save all the answers and type-specific options
303 $form->id = $question->id;
304 $form->qtype = $question->qtype;
305 $form->category = $question->category;
306 $form->questiontext = $question->questiontext;
308 $result = $this->save_question_options($form);
310 if (!empty($result->error)) {
311 error($result->error);
314 if (!empty($result->notice)) {
315 notice($result->notice, "question.php?id=$question->id");
318 if (!empty($result->noticeyesno)) {
319 notice_yesno($result->noticeyesno, "question.php?id=$question->id&amp;courseid={$course->id}",
320 "edit.php?courseid={$course->id}");
321 print_footer($course);
322 exit;
325 // Give the question a unique version stamp determined by question_hash()
326 if (!set_field('question', 'version', question_hash($question), 'id', $question->id)) {
327 error('Could not update question version field');
330 return $question;
334 * Saves question-type specific options
336 * This is called by {@link save_question()} to save the question-type specific data
337 * @return object $result->error or $result->noticeyesno or $result->notice
338 * @param object $question This holds the information from the editing form,
339 * it is not a standard question object.
341 function save_question_options($question) {
342 $extra_question_fields = $this->extra_question_fields();
344 if (is_array($extra_question_fields)) {
345 $question_extension_table = array_shift($extra_question_fields);
347 $function = 'update_record';
348 $options = get_record($question_extension_table, 'questionid', $question->id);
349 if (!$options) {
350 $function = 'insert_record';
351 $options = new stdClass;
352 $options->questionid = $question->id;
354 foreach ($extra_question_fields as $field) {
355 if (!isset($question->$field)) {
356 $result = new stdClass;
357 $result->error = "No data for field $field when saving " .
358 $this->name() . ' question id ' . $question->id;
359 return $result;
361 $options->$field = $question->$field;
364 if (!$function($question_extension_table, $options)) {
365 $result = new stdClass;
366 $result->error = 'Could not save question options for ' .
367 $this->name() . ' question id ' . $question->id;
368 return $result;
372 $extra_answer_fields = $this->extra_answer_fields();
373 // TODO save the answers, with any extra data.
375 return null;
379 * Changes all states for the given attempts over to a new question
381 * This is used by the versioning code if the teacher requests that a question
382 * gets replaced by the new version. In order for the attempts to be regraded
383 * properly all data in the states referring to the old question need to be
384 * changed to refer to the new version instead. In particular for question types
385 * that use the answers table the answers belonging to the old question have to
386 * be changed to those belonging to the new version.
388 * @param integer $oldquestionid The id of the old question
389 * @param object $newquestion The new question
390 * @param array $attempts An array of all attempt objects in whose states
391 * replacement should take place
393 function replace_question_in_attempts($oldquestionid, $newquestion, $attemtps) {
394 echo 'Not yet implemented';
395 return;
399 * Loads the question type specific options for the question.
401 * This function loads any question type specific options for the
402 * question from the database into the question object. This information
403 * is placed in the $question->options field. A question type is
404 * free, however, to decide on a internal structure of the options field.
405 * @return bool Indicates success or failure.
406 * @param object $question The question object for the question. This object
407 * should be updated to include the question type
408 * specific information (it is passed by reference).
410 function get_question_options(&$question) {
411 global $CFG;
413 if (!isset($question->options)) {
414 $question->options = new object;
417 $extra_question_fields = $this->extra_question_fields();
418 if (is_array($extra_question_fields)) {
419 $question_extension_table = array_shift($extra_question_fields);
420 $extra_data = get_record($question_extension_table, 'questionid', $question->id, '', '', '', '', implode(', ', $extra_question_fields));
421 if ($extra_data) {
422 foreach ($extra_question_fields as $field) {
423 $question->options->$field = $extra_data->$field;
425 } else {
426 notify("Failed to load question options from the table $question_extension_table for questionid " .
427 $question->id);
428 return false;
432 $extra_answer_fields = $this->extra_answer_fields();
433 if (is_array($extra_answer_fields)) {
434 $answer_extension_table = array_shift($extra_answer_fields);
435 $question->options->answers = get_records_sql('
436 SELECT qa.*, qax.' . implode(', qax.', $extra_answer_fields) . '
437 FROM ' . $CFG->prefix . 'question_answers qa, ' . $CFG->prefix . '$answer_extension_table qax
438 WHERE qa.questionid = ' . $question->id . ' AND qax.answerid = qa.id');
439 if (!$question->options->answers) {
440 notify("Failed to load question answers from the table $answer_extension_table for questionid " .
441 $question->id);
442 return false;
444 } else {
445 // Don't check for success or failure because some question types do not use the answers table.
446 $question->options->answers = get_records('question_answers', 'question', $question->id, 'id ASC');
449 return true;
453 * Deletes states from the question-type specific tables
455 * @param string $stateslist Comma separated list of state ids to be deleted
457 function delete_states($stateslist) {
458 /// The default question type does not have any tables of its own
459 // therefore there is nothing to delete
461 return true;
465 * Deletes a question from the question-type specific tables
467 * @return boolean Success/Failure
468 * @param object $question The question being deleted
470 function delete_question($questionid) {
471 global $CFG;
472 $success = true;
474 $extra_question_fields = $this->extra_question_fields();
475 if (is_array($extra_question_fields)) {
476 $question_extension_table = array_shift($extra_question_fields);
477 $success = $success && delete_records($question_extension_table, 'questionid', $questionid);
480 $extra_answer_fields = $this->extra_answer_fields();
481 if (is_array($extra_answer_fields)) {
482 $answer_extension_table = array_shift($extra_answer_fields);
483 $success = $success && delete_records_select($answer_extension_table,
484 "answerid IN (SELECT qa.id FROM {$CFG->prefix}question_answers qa WHERE qa.question = $questionid)");
487 $success = $success && delete_records('question_answers', 'question', $questionid);
489 return $success;
493 * Returns the number of question numbers which are used by the question
495 * This function returns the number of question numbers to be assigned
496 * to the question. Most question types will have length one; they will be
497 * assigned one number. The 'description' type, however does not use up a
498 * number and so has a length of zero. Other question types may wish to
499 * handle a bundle of questions and hence return a number greater than one.
500 * @return integer The number of question numbers which should be
501 * assigned to the question.
502 * @param object $question The question whose length is to be determined.
503 * Question type specific information is included.
505 function actual_number_of_questions($question) {
506 // By default, each question is given one number
507 return 1;
511 * Creates empty session and response information for the question
513 * This function is called to start a question session. Empty question type
514 * specific session data (if any) and empty response data will be added to the
515 * state object. Session data is any data which must persist throughout the
516 * attempt possibly with updates as the user interacts with the
517 * question. This function does NOT create new entries in the database for
518 * the session; a call to the {@link save_session_and_responses} member will
519 * occur to do this.
520 * @return bool Indicates success or failure.
521 * @param object $question The question for which the session is to be
522 * created. Question type specific information is
523 * included.
524 * @param object $state The state to create the session for. Note that
525 * this will not have been saved in the database so
526 * there will be no id. This object will be updated
527 * to include the question type specific information
528 * (it is passed by reference). In particular, empty
529 * responses will be created in the ->responses
530 * field.
531 * @param object $cmoptions
532 * @param object $attempt The attempt for which the session is to be
533 * started. Questions may wish to initialize the
534 * session in different ways depending on the user id
535 * or time available for the attempt.
537 function create_session_and_responses(&$question, &$state, $cmoptions, $attempt) {
538 // The default implementation should work for the legacy question types.
539 // Most question types with only a single form field for the student's response
540 // will use the empty string '' as the index for that one response. This will
541 // automatically be stored in and restored from the answer field in the
542 // question_states table.
543 $state->responses = array(
544 '' => '',
546 return true;
550 * Restores the session data and most recent responses for the given state
552 * This function loads any session data associated with the question
553 * session in the given state from the database into the state object.
554 * In particular it loads the responses that have been saved for the given
555 * state into the ->responses member of the state object.
557 * Question types with only a single form field for the student's response
558 * will not need not restore the responses; the value of the answer
559 * field in the question_states table is restored to ->responses['']
560 * before this function is called. Question types with more response fields
561 * should override this method and set the ->responses field to an
562 * associative array of responses.
563 * @return bool Indicates success or failure.
564 * @param object $question The question object for the question including any
565 * question type specific information.
566 * @param object $state The saved state to load the session for. This
567 * object should be updated to include the question
568 * type specific session information and responses
569 * (it is passed by reference).
571 function restore_session_and_responses(&$question, &$state) {
572 // The default implementation does nothing (successfully)
573 return true;
577 * Saves the session data and responses for the given question and state
579 * This function saves the question type specific session data from the
580 * state object to the database. In particular for most question types it saves the
581 * responses from the ->responses member of the state object. The question type
582 * non-specific data for the state has already been saved in the question_states
583 * table and the state object contains the corresponding id and
584 * sequence number which may be used to index a question type specific table.
586 * Question types with only a single form field for the student's response
587 * which is contained in ->responses[''] will not have to save this response,
588 * it will already have been saved to the answer field of the question_states table.
589 * Question types with more response fields should override this method and save
590 * the responses in their own database tables.
591 * @return bool Indicates success or failure.
592 * @param object $question The question object for the question including
593 * the question type specific information.
594 * @param object $state The state for which the question type specific
595 * data and responses should be saved.
597 function save_session_and_responses(&$question, &$state) {
598 // The default implementation does nothing (successfully)
599 return true;
603 * Returns an array of values which will give full marks if graded as
604 * the $state->responses field
606 * The correct answer to the question in the given state, or an example of
607 * a correct answer if there are many, is returned. This is used by some question
608 * types in the {@link grade_responses()} function but it is also used by the
609 * question preview screen to fill in correct responses.
610 * @return mixed A response array giving the responses corresponding
611 * to the (or a) correct answer to the question. If there is
612 * no correct answer that scores 100% then null is returned.
613 * @param object $question The question for which the correct answer is to
614 * be retrieved. Question type specific information is
615 * available.
616 * @param object $state The state of the question, for which a correct answer is
617 * needed. Question type specific information is included.
619 function get_correct_responses(&$question, &$state) {
620 /* The default implementation returns the response for the first answer
621 that gives full marks. */
622 if ($question->options->answers) {
623 foreach ($question->options->answers as $answer) {
624 if (((int) $answer->fraction) === 1) {
625 return array('' => addslashes($answer->answer));
629 return null;
633 * Return an array of values with the texts for all possible responses stored
634 * for the question
636 * All answers are found and their text values isolated
637 * @return object A mixed object
638 * ->id question id. Needed to manage random questions:
639 * it's the id of the actual question presented to user in a given attempt
640 * ->responses An array of values giving the responses corresponding
641 * to all answers to the question. Answer ids are used as keys.
642 * The text and partial credit are the object components
643 * @param object $question The question for which the answers are to
644 * be retrieved. Question type specific information is
645 * available.
647 // ULPGC ecastro
648 function get_all_responses(&$question, &$state) {
649 if (isset($question->options->answers) && is_array($question->options->answers)) {
650 $answers = array();
651 foreach ($question->options->answers as $aid=>$answer) {
652 $r = new stdClass;
653 $r->answer = $answer->answer;
654 $r->credit = $answer->fraction;
655 $answers[$aid] = $r;
657 $result = new stdClass;
658 $result->id = $question->id;
659 $result->responses = $answers;
660 return $result;
661 } else {
662 return null;
667 * Return the actual response to the question in a given state
668 * for the question
670 * @return mixed An array containing the response or reponses (multiple answer, match)
671 * given by the user in a particular attempt.
672 * @param object $question The question for which the correct answer is to
673 * be retrieved. Question type specific information is
674 * available.
675 * @param object $state The state object that corresponds to the question,
676 * for which a correct answer is needed. Question
677 * type specific information is included.
679 // ULPGC ecastro
680 function get_actual_response($question, $state) {
681 // change length to truncate responses here if you want
682 $lmax = 40;
683 if (!empty($state->responses)) {
684 $responses[] = (strlen($state->responses['']) > $lmax) ?
685 substr($state->responses[''], 0, $lmax).'...' : $state->responses[''];
686 } else {
687 $responses[] = '';
689 return $responses;
692 // ULPGC ecastro
693 function get_fractional_grade(&$question, &$state) {
694 $maxgrade = $question->maxgrade;
695 $grade = $state->grade;
696 if ($maxgrade) {
697 return (float)($grade/$maxgrade);
698 } else {
699 return (float)$grade;
705 * Checks if the response given is correct and returns the id
707 * @return int The ide number for the stored answer that matches the response
708 * given by the user in a particular attempt.
709 * @param object $question The question for which the correct answer is to
710 * be retrieved. Question type specific information is
711 * available.
712 * @param object $state The state object that corresponds to the question,
713 * for which a correct answer is needed. Question
714 * type specific information is included.
716 // ULPGC ecastro
717 function check_response(&$question, &$state){
718 return false;
721 // Used by the following function, so that it only returns results once per quiz page.
722 var $already_done = false;
724 * If this question type requires extra CSS or JavaScript to function,
725 * then this method will return an array of <link ...> tags that reference
726 * those stylesheets. This function will also call require_js()
727 * from ajaxlib.php, to get any necessary JavaScript linked in too.
729 * The two parameters match the first two parameters of print_question.
731 * @param object $question The question object.
732 * @param object $state The state object.
734 * @return an array of bits of HTML to add to the head of pages where
735 * this question is print_question-ed in the body. The array should use
736 * integer array keys, which have no significance.
738 function get_html_head_contributions(&$question, &$state) {
739 // By default, we link to any of the files styles.css, styles.php,
740 // script.js or script.php that exist in the plugin folder.
741 // Core question types should not use this mechanism. Their styles
742 // should be included in the standard theme.
745 // We only do this once
746 // for this question type, no matter how often this method is called.
747 if ($this->already_done) {
748 return array();
750 $this->already_done = true;
752 $plugindir = $this->plugin_dir();
753 $baseurl = $this->plugin_baseurl();
754 $stylesheets = array();
755 if (file_exists($plugindir . '/styles.css')) {
756 $stylesheets[] = 'styles.css';
758 if (file_exists($plugindir . '/styles.php')) {
759 $stylesheets[] = 'styles.php';
761 if (file_exists($plugindir . '/script.js')) {
762 require_js($baseurl . '/script.js');
764 if (file_exists($plugindir . '/script.php')) {
765 require_js($baseurl . '/script.php');
767 $contributions = array();
768 foreach ($stylesheets as $stylesheet) {
769 $contributions[] = '<link rel="stylesheet" type="text/css" href="' .
770 $baseurl . '/' . $stylesheet . '" />';
772 return $contributions;
776 * Prints the question including the number, grading details, content,
777 * feedback and interactions
779 * This function prints the question including the question number,
780 * grading details, content for the question, any feedback for the previously
781 * submitted responses and the interactions. The default implementation calls
782 * various other methods to print each of these parts and most question types
783 * will just override those methods.
784 * @param object $question The question to be rendered. Question type
785 * specific information is included. The
786 * maximum possible grade is in ->maxgrade. The name
787 * prefix for any named elements is in ->name_prefix.
788 * @param object $state The state to render the question in. The grading
789 * information is in ->grade, ->raw_grade and
790 * ->penalty. The current responses are in
791 * ->responses. This is an associative array (or the
792 * empty string or null in the case of no responses
793 * submitted). The last graded state is in
794 * ->last_graded (hence the most recently graded
795 * responses are in ->last_graded->responses). The
796 * question type specific information is also
797 * included.
798 * @param integer $number The number for this question.
799 * @param object $cmoptions
800 * @param object $options An object describing the rendering options.
802 function print_question(&$question, &$state, $number, $cmoptions, $options) {
803 /* The default implementation should work for most question types
804 provided the member functions it calls are overridden where required.
805 The layout is determined by the template question.html */
807 global $CFG;
808 $isgraded = question_state_is_graded($state->last_graded);
810 // get the context so we can determine whether some extra links
811 // should be shown.
812 if (!empty($cmoptions->id)) {
813 $cm = get_coursemodule_from_instance('quiz', $cmoptions->id);
814 $context = get_context_instance(CONTEXT_MODULE, $cm->id);
815 $cmorcourseid = '&amp;cmid='.$cm->id;
816 } else if (!empty($cmoptions->course)) {
817 $context = get_context_instance(CONTEXT_COURSE, $cmoptions->course);
818 $cmorcourseid = '&amp;courseid='.$cmoptions->course;
819 } else {
820 error('Need to provide courseid or cmid to print_question.');
823 // For editing teachers print a link to an editing popup window
824 $editlink = '';
825 if (question_has_capability_on($question, 'edit')) {
826 $stredit = get_string('edit');
827 $linktext = '<img src="'.$CFG->pixpath.'/t/edit.gif" alt="'.$stredit.'" />';
828 $editlink = link_to_popup_window('/question/question.php?inpopup=1&amp;id='.$question->id.$cmorcourseid,
829 'editquestion', $linktext, 450, 550, $stredit, '', true);
832 $generalfeedback = '';
833 if ($isgraded && $options->generalfeedback) {
834 $generalfeedback = $this->format_text($question->generalfeedback,
835 $question->questiontextformat, $cmoptions);
838 $grade = '';
839 if ($question->maxgrade and $options->scores) {
840 if ($cmoptions->optionflags & QUESTION_ADAPTIVE) {
841 $grade = !$isgraded ? '--/' : round($state->last_graded->grade, $cmoptions->decimalpoints).'/';
843 $grade .= $question->maxgrade;
846 $comment = stripslashes($state->manualcomment);
847 $commentlink = '';
849 if (isset($options->questioncommentlink) && $context && has_capability('mod/quiz:grade', $context)) {
850 $strcomment = get_string('commentorgrade', 'quiz');
851 $commentlink = '<div class="commentlink">'.link_to_popup_window ($options->questioncommentlink.'?attempt='.$state->attempt.'&amp;question='.$question->id,
852 'commentquestion', $strcomment, 450, 650, $strcomment, 'none', true).'</div>';
855 $history = $this->history($question, $state, $number, $cmoptions, $options);
857 include "$CFG->dirroot/question/type/question.html";
861 * Print history of responses
863 * Used by print_question()
865 function history($question, $state, $number, $cmoptions, $options) {
866 $history = '';
867 if(isset($options->history) and $options->history) {
868 if ($options->history == 'all') {
869 // show all states
870 $states = get_records_select('question_states', "attempt = '$state->attempt' AND question = '$question->id' AND event > '0'", 'seq_number ASC');
871 } else {
872 // show only graded states
873 $states = get_records_select('question_states', "attempt = '$state->attempt' AND question = '$question->id' AND event IN (".QUESTION_EVENTGRADE.','.QUESTION_EVENTCLOSEANDGRADE.")", 'seq_number ASC');
875 if (count($states) > 1) {
876 $strreviewquestion = get_string('reviewresponse', 'quiz');
877 $table = new stdClass;
878 $table->width = '100%';
879 if ($options->scores) {
880 $table->head = array (
881 get_string('numberabbr', 'quiz'),
882 get_string('action', 'quiz'),
883 get_string('response', 'quiz'),
884 get_string('time'),
885 get_string('score', 'quiz'),
886 //get_string('penalty', 'quiz'),
887 get_string('grade', 'quiz'),
889 } else {
890 $table->head = array (
891 get_string('numberabbr', 'quiz'),
892 get_string('action', 'quiz'),
893 get_string('response', 'quiz'),
894 get_string('time'),
898 foreach ($states as $st) {
899 $st->responses[''] = $st->answer;
900 $this->restore_session_and_responses($question, $st);
901 $b = ($state->id == $st->id) ? '<b>' : '';
902 $be = ($state->id == $st->id) ? '</b>' : '';
903 if ($state->id == $st->id) {
904 $link = '<b>'.$st->seq_number.'</b>';
905 } else {
906 if(isset($options->questionreviewlink)) {
907 $link = link_to_popup_window ($options->questionreviewlink.'?state='.$st->id.'&amp;number='.$number,
908 'reviewquestion', $st->seq_number, 450, 650, $strreviewquestion, 'none', true);
909 } else {
910 $link = $st->seq_number;
913 if ($options->scores) {
914 $table->data[] = array (
915 $link,
916 $b.get_string('event'.$st->event, 'quiz').$be,
917 $b.$this->response_summary($question, $st).$be,
918 $b.userdate($st->timestamp, get_string('timestr', 'quiz')).$be,
919 $b.round($st->raw_grade, $cmoptions->decimalpoints).$be,
920 //$b.round($st->penalty, $cmoptions->decimalpoints).$be,
921 $b.round($st->grade, $cmoptions->decimalpoints).$be
923 } else {
924 $table->data[] = array (
925 $link,
926 $b.get_string('event'.$st->event, 'quiz').$be,
927 $b.$this->response_summary($question, $st).$be,
928 $b.userdate($st->timestamp, get_string('timestr', 'quiz')).$be,
932 $history = make_table($table);
935 return $history;
940 * Prints the score obtained and maximum score available plus any penalty
941 * information
943 * This function prints a summary of the scoring in the most recently
944 * graded state (the question may not have been submitted for marking at
945 * the current state). The default implementation should be suitable for most
946 * question types.
947 * @param object $question The question for which the grading details are
948 * to be rendered. Question type specific information
949 * is included. The maximum possible grade is in
950 * ->maxgrade.
951 * @param object $state The state. In particular the grading information
952 * is in ->grade, ->raw_grade and ->penalty.
953 * @param object $cmoptions
954 * @param object $options An object describing the rendering options.
956 function print_question_grading_details(&$question, &$state, $cmoptions, $options) {
957 /* The default implementation prints the number of marks if no attempt
958 has been made. Otherwise it displays the grade obtained out of the
959 maximum grade available and a warning if a penalty was applied for the
960 attempt and displays the overall grade obtained counting all previous
961 responses (and penalties) */
963 if (QUESTION_EVENTDUPLICATE == $state->event) {
964 echo ' ';
965 print_string('duplicateresponse', 'quiz');
967 if (!empty($question->maxgrade) && $options->scores) {
968 if (question_state_is_graded($state->last_graded)) {
969 // Display the grading details from the last graded state
970 $grade = new stdClass;
971 $grade->cur = round($state->last_graded->grade, $cmoptions->decimalpoints);
972 $grade->max = $question->maxgrade;
973 $grade->raw = round($state->last_graded->raw_grade, $cmoptions->decimalpoints);
975 // let student know wether the answer was correct
976 echo '<div class="correctness ';
977 if ($state->last_graded->raw_grade >= $question->maxgrade/1.01) { // We divide by 1.01 so that rounding errors dont matter.
978 echo ' correct">';
979 print_string('correct', 'quiz');
980 } else if ($state->last_graded->raw_grade > 0) {
981 echo ' partiallycorrect">';
982 print_string('partiallycorrect', 'quiz');
983 } else {
984 echo ' incorrect">';
985 print_string('incorrect', 'quiz');
987 echo '</div>';
989 echo '<div class="gradingdetails">';
990 // print grade for this submission
991 print_string('gradingdetails', 'quiz', $grade);
992 if ($cmoptions->penaltyscheme) {
993 // print details of grade adjustment due to penalties
994 if ($state->last_graded->raw_grade > $state->last_graded->grade){
995 echo ' ';
996 print_string('gradingdetailsadjustment', 'quiz', $grade);
998 // print info about new penalty
999 // penalty is relevant only if the answer is not correct and further attempts are possible
1000 if (($state->last_graded->raw_grade < $question->maxgrade / 1.01)
1001 and (QUESTION_EVENTCLOSEANDGRADE !== $state->event)) {
1003 if ('' !== $state->last_graded->penalty && ((float)$state->last_graded->penalty) > 0.0) {
1004 // A penalty was applied so display it
1005 echo ' ';
1006 print_string('gradingdetailspenalty', 'quiz', $state->last_graded->penalty);
1007 } else {
1008 /* No penalty was applied even though the answer was
1009 not correct (eg. a syntax error) so tell the student
1010 that they were not penalised for the attempt */
1011 echo ' ';
1012 print_string('gradingdetailszeropenalty', 'quiz');
1016 echo '</div>';
1022 * Prints the main content of the question including any interactions
1024 * This function prints the main content of the question including the
1025 * interactions for the question in the state given. The last graded responses
1026 * are printed or indicated and the current responses are selected or filled in.
1027 * Any names (eg. for any form elements) are prefixed with $question->name_prefix.
1028 * This method is called from the print_question method.
1029 * @param object $question The question to be rendered. Question type
1030 * specific information is included. The name
1031 * prefix for any named elements is in ->name_prefix.
1032 * @param object $state The state to render the question in. The grading
1033 * information is in ->grade, ->raw_grade and
1034 * ->penalty. The current responses are in
1035 * ->responses. This is an associative array (or the
1036 * empty string or null in the case of no responses
1037 * submitted). The last graded state is in
1038 * ->last_graded (hence the most recently graded
1039 * responses are in ->last_graded->responses). The
1040 * question type specific information is also
1041 * included.
1042 * The state is passed by reference because some adaptive
1043 * questions may want to update it during rendering
1044 * @param object $cmoptions
1045 * @param object $options An object describing the rendering options.
1047 function print_question_formulation_and_controls(&$question, &$state, $cmoptions, $options) {
1048 /* This default implementation prints an error and must be overridden
1049 by all question type implementations, unless the default implementation
1050 of print_question has been overridden. */
1052 notify('Error: Question formulation and input controls has not'
1053 .' been implemented for question type '.$this->name());
1057 * Prints the submit button(s) for the question in the given state
1059 * This function prints the submit button(s) for the question in the
1060 * given state. The name of any button created will be prefixed with the
1061 * unique prefix for the question in $question->name_prefix. The suffix
1062 * 'submit' is reserved for the single question submit button and the suffix
1063 * 'validate' is reserved for the single question validate button (for
1064 * question types which support it). Other suffixes will result in a response
1065 * of that name in $state->responses which the printing and grading methods
1066 * can then use.
1067 * @param object $question The question for which the submit button(s) are to
1068 * be rendered. Question type specific information is
1069 * included. The name prefix for any
1070 * named elements is in ->name_prefix.
1071 * @param object $state The state to render the buttons for. The
1072 * question type specific information is also
1073 * included.
1074 * @param object $cmoptions
1075 * @param object $options An object describing the rendering options.
1077 function print_question_submit_buttons(&$question, &$state, $cmoptions, $options) {
1078 /* The default implementation should be suitable for most question
1079 types. It prints a mark button in the case where individual marking is
1080 allowed. */
1082 if (($cmoptions->optionflags & QUESTION_ADAPTIVE) and !$options->readonly) {
1083 echo '<input type="submit" name="', $question->name_prefix, 'submit" value="',
1084 get_string('mark', 'quiz'), '" class="submit btn" onclick="',
1085 "form.action = form.action + '#q", $question->id, "'; return true;", '" />';
1090 * Return a summary of the student response
1092 * This function returns a short string of no more than a given length that
1093 * summarizes the student's response in the given $state. This is used for
1094 * example in the response history table
1095 * @return string The summary of the student response
1096 * @param object $question
1097 * @param object $state The state whose responses are to be summarized
1098 * @param int $length The maximum length of the returned string
1100 function response_summary($question, $state, $length=80) {
1101 // This should almost certainly be overridden
1102 $responses = $this->get_actual_response($question, $state);
1103 if (empty($responses) || !is_array($responses)) {
1104 $responses = array();
1106 if (is_array($responses)) {
1107 $responses = implode(',', $responses);
1109 return substr($responses, 0, $length);
1113 * Renders the question for printing and returns the LaTeX source produced
1115 * This function should render the question suitable for a printed problem
1116 * or solution sheet in LaTeX and return the rendered output.
1117 * @return string The LaTeX output.
1118 * @param object $question The question to be rendered. Question type
1119 * specific information is included.
1120 * @param object $state The state to render the question in. The
1121 * question type specific information is also
1122 * included.
1123 * @param object $cmoptions
1124 * @param string $type Indicates if the question or the solution is to be
1125 * rendered with the values 'question' and
1126 * 'solution'.
1128 function get_texsource(&$question, &$state, $cmoptions, $type) {
1129 // The default implementation simply returns a string stating that
1130 // the question is only available online.
1132 return get_string('onlineonly', 'texsheet');
1136 * Compares two question states for equivalence of the student's responses
1138 * The responses for the two states must be examined to see if they represent
1139 * equivalent answers to the question by the student. This method will be
1140 * invoked for each of the previous states of the question before grading
1141 * occurs. If the student is found to have already attempted the question
1142 * with equivalent responses then the attempt at the question is ignored;
1143 * grading does not occur and the state does not change. Thus they are not
1144 * penalized for this case.
1145 * @return boolean
1146 * @param object $question The question for which the states are to be
1147 * compared. Question type specific information is
1148 * included.
1149 * @param object $state The state of the question. The responses are in
1150 * ->responses. This is the only field of $state
1151 * that it is safe to use.
1152 * @param object $teststate The state whose responses are to be
1153 * compared. The state will be of the same age or
1154 * older than $state. If possible, the method should
1155 * only use the field $teststate->responses, however
1156 * any field that is set up by restore_session_and_responses
1157 * can be used.
1159 function compare_responses(&$question, $state, $teststate) {
1160 // The default implementation performs a comparison of the response
1161 // arrays. The ordering of the arrays does not matter.
1162 // Question types may wish to override this (eg. to ignore trailing
1163 // white space or to make "7.0" and "7" compare equal).
1165 // In php neither == nor === compare arrays the way you want. The following
1166 // ensures that the arrays have the same keys, with the same values.
1167 $result = false;
1168 $diff1 = array_diff_assoc($state->responses, $teststate->responses);
1169 if (empty($diff1)) {
1170 $diff2 = array_diff_assoc($teststate->responses, $state->responses);
1171 $result = empty($diff2);
1174 return $result;
1178 * Checks whether a response matches a given answer
1180 * This method only applies to questions that use teacher-defined answers
1182 * @return boolean
1184 function test_response(&$question, &$state, $answer) {
1185 $response = isset($state->responses['']) ? $state->responses[''] : '';
1186 return ($response == $answer->answer);
1190 * Performs response processing and grading
1192 * This function performs response processing and grading and updates
1193 * the state accordingly.
1194 * @return boolean Indicates success or failure.
1195 * @param object $question The question to be graded. Question type
1196 * specific information is included.
1197 * @param object $state The state of the question to grade. The current
1198 * responses are in ->responses. The last graded state
1199 * is in ->last_graded (hence the most recently graded
1200 * responses are in ->last_graded->responses). The
1201 * question type specific information is also
1202 * included. The ->raw_grade and ->penalty fields
1203 * must be updated. The method is able to
1204 * close the question session (preventing any further
1205 * attempts at this question) by setting
1206 * $state->event to QUESTION_EVENTCLOSEANDGRADE
1207 * @param object $cmoptions
1209 function grade_responses(&$question, &$state, $cmoptions) {
1210 // The default implementation uses the test_response method to
1211 // compare what the student entered against each of the possible
1212 // answers stored in the question, and uses the grade from the
1213 // first one that matches. It also sets the marks and penalty.
1214 // This should be good enought for most simple question types.
1216 $state->raw_grade = 0;
1217 foreach($question->options->answers as $answer) {
1218 if($this->test_response($question, $state, $answer)) {
1219 $state->raw_grade = $answer->fraction;
1220 break;
1224 // Make sure we don't assign negative or too high marks.
1225 $state->raw_grade = min(max((float) $state->raw_grade,
1226 0.0), 1.0) * $question->maxgrade;
1228 // Update the penalty.
1229 $state->penalty = $question->penalty * $question->maxgrade;
1231 // mark the state as graded
1232 $state->event = ($state->event == QUESTION_EVENTCLOSE) ? QUESTION_EVENTCLOSEANDGRADE : QUESTION_EVENTGRADE;
1234 return true;
1239 * Includes configuration settings for the question type on the quiz admin
1240 * page
1242 * TODO: It makes no sense any longer to do the admin for question types
1243 * from the quiz admin page. This should be changed.
1244 * Returns an array of objects describing the options for the question type
1245 * to be included on the quiz module admin page.
1246 * Configuration options can be included by setting the following fields in
1247 * the object:
1248 * ->name The name of the option within this question type.
1249 * The full option name will be constructed as
1250 * "quiz_{$this->name()}_$name", the human readable name
1251 * will be displayed with get_string($name, 'quiz').
1252 * ->code The code to display the form element, help button, etc.
1253 * i.e. the content for the central table cell. Be sure
1254 * to name the element "quiz_{$this->name()}_$name" and
1255 * set the value to $CFG->{"quiz_{$this->name()}_$name"}.
1256 * ->help Name of the string from the quiz module language file
1257 * to be used for the help message in the third column of
1258 * the table. An empty string (or the field not set)
1259 * means to leave the box empty.
1260 * Links to custom settings pages can be included by setting the following
1261 * fields in the object:
1262 * ->name The name of the link text string.
1263 * get_string($name, 'quiz') will be called.
1264 * ->link The filename part of the URL for the link. The full URL
1265 * is contructed as
1266 * "$CFG->wwwroot/question/type/{$this->name()}/$link?sesskey=$sesskey"
1267 * [but with the relavant calls to the s and rawurlencode
1268 * functions] where $sesskey is the sesskey for the user.
1269 * @return array Array of objects describing the configuration options to
1270 * be included on the quiz module admin page.
1272 function get_config_options() {
1273 // No options by default
1275 return false;
1279 * Returns true if the editing wizard is finished, false otherwise.
1281 * The default implementation returns true, which is suitable for all question-
1282 * types that only use one editing form. This function is used in
1283 * question.php to decide whether we can regrade any states of the edited
1284 * question and redirect to edit.php.
1286 * The dataset dependent question-type, which is extended by the calculated
1287 * question-type, overwrites this method because it uses multiple pages (i.e.
1288 * a wizard) to set up the question and associated datasets.
1290 * @param object $form The data submitted by the previous page.
1292 * @return boolean Whether the wizard's last page was submitted or not.
1294 function finished_edit_wizard(&$form) {
1295 //In the default case there is only one edit page.
1296 return true;
1300 * Prints a table of course modules in which the question is used
1302 * TODO: This should be made quiz-independent
1304 * This function is used near the end of the question edit forms in all question types
1305 * It prints the table of quizzes in which the question is used
1306 * containing checkboxes to allow the teacher to replace the old question version
1308 * @param object $question
1309 * @param object $course
1310 * @param integer $cmid optional The id of the course module currently being edited
1312 function print_replacement_options($question, $course, $cmid='0') {
1314 // Disable until the versioning code has been fixed
1315 if (true) {
1316 return;
1319 // no need to display replacement options if the question is new
1320 if(empty($question->id)) {
1321 return true;
1324 // get quizzes using the question (using the question_instances table)
1325 $quizlist = array();
1326 if(!$instances = get_records('quiz_question_instances', 'question', $question->id)) {
1327 $instances = array();
1329 foreach($instances as $instance) {
1330 $quizlist[$instance->quiz] = $instance->quiz;
1332 $quizlist = implode(',', $quizlist);
1333 if(empty($quizlist) or !$quizzes = get_records_list('quiz', 'id', $quizlist)) {
1334 $quizzes = array();
1337 // do the printing
1338 if(count($quizzes) > 0) {
1339 // print the table
1340 $strquizname = get_string('modulename', 'quiz');
1341 $strdoreplace = get_string('replace', 'quiz');
1342 $straffectedstudents = get_string('affectedstudents', 'quiz', $course->students);
1343 echo "<tr valign=\"top\">\n";
1344 echo "<td align=\"right\"><b>".get_string("replacementoptions", "quiz").":</b></td>\n";
1345 echo "<td align=\"left\">\n";
1346 echo "<table cellpadding=\"5\" align=\"left\" class=\"generalbox\" width=\"100%\">\n";
1347 echo "<tr>\n";
1348 echo "<th align=\"left\" valign=\"top\" nowrap=\"nowrap\" class=\"generaltableheader c0\" scope=\"col\">$strquizname</th>\n";
1349 echo "<th align=\"center\" valign=\"top\" nowrap=\"nowrap\" class=\"generaltableheader c0\" scope=\"col\">$strdoreplace</th>\n";
1350 echo "<th align=\"left\" valign=\"top\" nowrap=\"nowrap\" class=\"generaltableheader c0\" scope=\"col\">$straffectedstudents</th>\n";
1351 echo "</tr>\n";
1352 foreach($quizzes as $quiz) {
1353 // work out whethere it should be checked by default
1354 $checked = '';
1355 if((int)$cmid === (int)$quiz->id
1356 or empty($quiz->usercount)) {
1357 $checked = "checked=\"checked\"";
1360 // find how many different students have already attempted this quiz
1361 $students = array();
1362 if($attempts = get_records_select('quiz_attempts', "quiz = '$quiz->id' AND preview = '0'")) {
1363 foreach($attempts as $attempt) {
1364 if (record_exists('question_states', 'attempt', $attempt->uniqueid, 'question', $question->id, 'originalquestion', 0)) {
1365 $students[$attempt->userid] = 1;
1369 $studentcount = count($students);
1371 $strstudents = $studentcount === 1 ? $course->student : $course->students;
1372 echo "<tr>\n";
1373 echo "<td align=\"left\" class=\"generaltablecell c0\">".format_string($quiz->name)."</td>\n";
1374 echo "<td align=\"center\" class=\"generaltablecell c0\"><input name=\"q{$quiz->id}replace\" type=\"checkbox\" ".$checked." /></td>\n";
1375 echo "<td align=\"left\" class=\"generaltablecell c0\">".(($studentcount) ? $studentcount.' '.$strstudents : '-')."</td>\n";
1376 echo "</tr>\n";
1378 echo "</table>\n";
1380 echo "</td></tr>\n";
1384 * Call format_text from weblib.php with the options appropriate to question types.
1386 * @param string $text the text to format.
1387 * @param integer $text the type of text. Normally $question->questiontextformat.
1388 * @param object $cmoptions the context the string is being displayed in. Only $cmoptions->course is used.
1389 * @return string the formatted text.
1391 function format_text($text, $textformat, $cmoptions = NULL) {
1392 $formatoptions = new stdClass;
1393 $formatoptions->noclean = true;
1394 $formatoptions->para = false;
1395 return format_text($text, $textformat, $formatoptions, $cmoptions === NULL ? NULL : $cmoptions->course);
1399 * Find all course / site files linked from a question.
1401 * Need to check for links to files in question_answers.answer and feedback
1402 * and in question table in generalfeedback and questiontext fields. Methods
1403 * on child classes will also check extra question specific fields.
1405 * Needs to be overriden for child classes that have extra fields containing
1406 * html.
1408 * @param string html the html to search
1409 * @param int courseid search for files for courseid course or set to siteid for
1410 * finding site files.
1411 * @return array of url, relative url is key and array with one item = question id as value
1412 * relative url is relative to course/site files directory root.
1414 function find_file_links($question, $courseid){
1415 $urls = array();
1416 if ($question->image != ''){
1417 if (substr(strtolower($question->image), 0, 7) == 'http://') {
1418 $matches = array();
1420 //support for older questions where we have a complete url in image field
1421 if (preg_match('!^'.question_file_links_base_url($courseid).'(.*)!i', $question->image, $matches)){
1422 if ($cleanedurl = question_url_check($urls[$matches[2]])){
1423 $urls[$cleanedurl] = null;
1426 } else {
1427 if ($question->image != ''){
1428 if ($cleanedurl = question_url_check($question->image)){
1429 $urls[$cleanedurl] = null;//will be set later
1436 $urls += question_find_file_links_from_html($question->questiontext, $courseid);
1437 $urls += question_find_file_links_from_html($question->generalfeedback, $courseid);
1438 if ($this->has_html_answers() && isset($question->options->answers)){
1439 foreach ($question->options->answers as $answerkey => $answer){
1440 $thisurls= question_find_file_links_from_html($answer->answer, $courseid);
1441 if ($thisurls){
1442 $urls += $thisurls;
1446 //set all the values of the array to the question object
1447 if ($urls){
1448 $urls = array_combine(array_keys($urls), array_fill(0, count($urls), array($question->id)));
1450 return $urls;
1453 * Find all course / site files linked from a question.
1455 * Need to check for links to files in question_answers.answer and feedback
1456 * and in question table in generalfeedback and questiontext fields. Methods
1457 * on child classes will also check extra question specific fields.
1459 * Needs to be overriden for child classes that have extra fields containing
1460 * html.
1462 * @param string html the html to search
1463 * @param int course search for files for courseid course or set to siteid for
1464 * finding site files.
1465 * @return array of files, file name is key and array with one item = question id as value
1467 function replace_file_links($question, $fromcourseid, $tocourseid, $url, $destination){
1468 global $CFG;
1469 $updateqrec = false;
1470 if (!empty($question->image)){
1471 //support for older questions where we have a complete url in image field
1472 if (substr(strtolower($question->image), 0, 7) == 'http://') {
1473 $questionimage = preg_replace('!^'.question_file_links_base_url($fromcourseid).preg_quote($url, '!').'$!i', $destination, $question->image, 1);
1474 } else {
1475 $questionimage = preg_replace('!^'.preg_quote($url, '!').'$!i', $destination, $question->image, 1);
1477 if ($questionimage != $question->image){
1478 $question->image = $questionimage;
1479 $updateqrec = true;
1482 $question->questiontext = question_replace_file_links_in_html($question->questiontext, $fromcourseid, $tocourseid, $url, $destination, $updateqrec);
1483 $question->generalfeedback = question_replace_file_links_in_html($question->generalfeedback, $fromcourseid, $tocourseid, $url, $destination, $updateqrec);
1484 if ($updateqrec){
1485 if (!update_record('question', addslashes_recursive($question))){
1486 error ('Couldn\'t update question '.$question->name);
1490 if ($this->has_html_answers() && isset($question->options->answers)){
1491 //answers that do not need updating have been unset
1492 foreach ($question->options->answers as $answer){
1493 $answerchanged = false;
1494 $answer->answer = question_replace_file_links_in_html($answer->answer, $fromcourseid, $tocourseid, $url, $destination, $answerchanged);
1495 if ($answerchanged){
1496 if (!update_record('question_answers', addslashes_recursive($answer))){
1497 error ('Couldn\'t update question ('.$question->name.') answer '.$answer->id);
1504 * @return the best link to pass to print_error.
1505 * @param $cmoptions as passed in from outside.
1507 function error_link($cmoptions) {
1508 global $CFG;
1509 $cm = get_coursemodule_from_instance('quiz', $cmoptions->id);
1510 if (!empty($cm->id)) {
1511 return $CFG->wwwroot . '/mod/quiz/view.php?id=' . $cm->id;
1512 } else if (!empty($cm->course)) {
1513 return $CFG->wwwroot . '/course/view.php?id=' . $cm->course;
1514 } else {
1515 return '';
1519 /// BACKUP FUNCTIONS ////////////////////////////
1522 * Backup the data in the question
1524 * This is used in question/backuplib.php
1526 function backup($bf,$preferences,$question,$level=6) {
1527 // The default type has nothing to back up
1528 return true;
1531 /// RESTORE FUNCTIONS /////////////////
1534 * Restores the data in the question
1536 * This is used in question/restorelib.php
1538 function restore($old_question_id,$new_question_id,$info,$restore) {
1539 // The default question type has nothing to restore
1540 return true;
1543 function restore_map($old_question_id,$new_question_id,$info,$restore) {
1544 // There is nothing to decode
1545 return true;
1548 function restore_recode_answer($state, $restore) {
1549 // There is nothing to decode
1550 return $state->answer;