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');
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
{
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.
47 * The name this question should appear as in the create new question
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');
64 * @return boolean true if this question can only be graded manually.
66 function is_manual_graded() {
71 * @return boolean true if this question type can be used by the random question type.
73 function is_usable_by_random() {
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() {
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() {
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() {
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) {
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))) {
124 require_once($definition_file);
125 $classname = 'question_edit_'.$this->name().'_form';
126 if (!class_exists($classname)) {
129 return new $classname($submiturl, $question);
133 * @return string the full path of the folder this plugin's files live in.
135 function plugin_dir() {
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() {
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();
158 print_heading_with_help($heading, $this->name(), $langmodule);
163 * Method called by display_question_editing_page and by question.php to get heading for breadcrumbs.
165 * @return array a string heading and the langmodule in which it was found.
167 function get_heading(){
168 $name = $this->name();
169 $langmodule = 'qtype_' . $name;
170 $strheading = get_string('editing' . $name, $langmodule);
171 if ($strheading[0] == '[') {
172 // Legacy behavior, if the string was not in the proper qtype_name
173 // language file, look it up in the quiz one.
174 $langmodule = 'quiz';
175 $strheading = get_string('editing' . $name, $langmodule);
177 return array($strheading, $langmodule);
185 function set_default_options(&$question) {
189 * Saves or updates a question after editing by a teacher
191 * Given some question info and some data about the answers
192 * this function parses, organises and saves the question
193 * It is used by {@link question.php} when saving new data from
194 * a form, and also by {@link import.php} when importing questions
195 * This function in turn calls {@link save_question_options}
196 * to save question-type specific options
197 * @param object $question the question object which should be updated
198 * @param object $form the form submitted by the teacher
199 * @param object $course the course we are in
200 * @return object On success, return the new question object. On failure,
201 * return an object as follows. If the error object has an errors field,
202 * display that as an error message. Otherwise, the editing form will be
203 * redisplayed with validation errors, from validation_errors field, which
204 * is itself an object, shown next to the form fields.
206 function save_question($question, $form, $course) {
207 // This default implementation is suitable for most
210 // First, save the basic question itself
211 if (!record_exists('question_categories', 'id', $form->category
)) {
212 print_error('categorydoesnotexist', 'question');
214 $question->category
= $form->category
;
215 $question->name
= trim($form->name
);
216 $question->questiontext
= trim($form->questiontext
);
217 $question->questiontextformat
= $form->questiontextformat
;
218 $question->parent
= isset($form->parent
)?
$form->parent
: 0;
219 $question->length
= $this->actual_number_of_questions($question);
220 $question->penalty
= isset($form->penalty
) ?
$form->penalty
: 0;
222 if (empty($form->image
)) {
223 $question->image
= "";
225 $question->image
= $form->image
;
228 if (empty($form->generalfeedback
)) {
229 $question->generalfeedback
= '';
231 $question->generalfeedback
= trim($form->generalfeedback
);
234 if (empty($question->name
)) {
235 $question->name
= substr(strip_tags($question->questiontext
), 0, 15);
236 if (empty($question->name
)) {
237 $question->name
= '-';
241 if ($question->penalty
> 1 or $question->penalty
< 0) {
242 $question->errors
['penalty'] = get_string('invalidpenalty', 'quiz');
245 if (isset($form->defaultgrade
)) {
246 $question->defaultgrade
= $form->defaultgrade
;
249 if (!empty($question->id
)) { // Question already exists
250 // keep existing unique stamp code
251 $question->stamp
= get_field('question', 'stamp', 'id', $question->id
);
252 if (!update_record("question", $question)) {
253 error("Could not update question!");
255 } else { // Question is a new one
256 // Set the unique code
257 $question->stamp
= make_unique_id_code();
258 if (!$question->id
= insert_record("question", $question)) {
259 error("Could not insert new question!");
263 // Now to save all the answers and type-specific options
265 $form->id
= $question->id
;
266 $form->qtype
= $question->qtype
;
267 $form->category
= $question->category
;
268 $form->questiontext
= $question->questiontext
;
270 $result = $this->save_question_options($form);
272 if (!empty($result->error
)) {
273 error($result->error
);
276 if (!empty($result->notice
)) {
277 notice($result->notice
, "question.php?id=$question->id");
280 if (!empty($result->noticeyesno
)) {
281 notice_yesno($result->noticeyesno
, "question.php?id=$question->id&courseid={$course->id}",
282 "edit.php?courseid={$course->id}");
283 print_footer($course);
287 // Give the question a unique version stamp determined by question_hash()
288 if (!set_field('question', 'version', question_hash($question), 'id', $question->id
)) {
289 error('Could not update question version field');
296 * Saves question-type specific options
298 * This is called by {@link save_question()} to save the question-type specific data
299 * @return object $result->error or $result->noticeyesno or $result->notice
300 * @param object $question This holds the information from the editing form,
301 * it is not a standard question object.
303 function save_question_options($question) {
304 $extra_question_fields = $this->extra_question_fields();
306 if (is_array($extra_question_fields)) {
307 $question_extension_table = array_shift($extra_question_fields);
309 $function = 'update_record';
310 $options = get_record($question_extension_table, 'questionid', $question->id
);
312 $function = 'insert_record';
313 $options = new stdClass
;
314 $options->questionid
= $question->id
;
316 foreach ($extra_question_fields as $field) {
317 if (!isset($question->$field)) {
318 $result = new stdClass
;
319 $result->error
= "No data for field $field when saving " .
320 $this->name() . ' question id ' . $question->id
;
323 $options->$field = $question->$field;
326 if (!$function($question_extension_table, $options)) {
327 $result = new stdClass
;
328 $result->error
= 'Could not save question options for ' .
329 $this->name() . ' question id ' . $question->id
;
334 $extra_answer_fields = $this->extra_answer_fields();
335 // TODO save the answers, with any extra data.
341 * Changes all states for the given attempts over to a new question
343 * This is used by the versioning code if the teacher requests that a question
344 * gets replaced by the new version. In order for the attempts to be regraded
345 * properly all data in the states referring to the old question need to be
346 * changed to refer to the new version instead. In particular for question types
347 * that use the answers table the answers belonging to the old question have to
348 * be changed to those belonging to the new version.
350 * @param integer $oldquestionid The id of the old question
351 * @param object $newquestion The new question
352 * @param array $attempts An array of all attempt objects in whose states
353 * replacement should take place
355 function replace_question_in_attempts($oldquestionid, $newquestion, $attemtps) {
356 echo 'Not yet implemented';
361 * Loads the question type specific options for the question.
363 * This function loads any question type specific options for the
364 * question from the database into the question object. This information
365 * is placed in the $question->options field. A question type is
366 * free, however, to decide on a internal structure of the options field.
367 * @return bool Indicates success or failure.
368 * @param object $question The question object for the question. This object
369 * should be updated to include the question type
370 * specific information (it is passed by reference).
372 function get_question_options(&$question) {
375 if (!isset($question->options
)) {
376 $question->options
= new object;
379 $extra_question_fields = $this->extra_question_fields();
380 if (is_array($extra_question_fields)) {
381 $question_extension_table = array_shift($extra_question_fields);
382 $extra_data = get_record($question_extension_table, 'questionid', $question->id
, '', '', '', '', implode(', ', $extra_question_fields));
384 foreach ($extra_question_fields as $field) {
385 $question->options
->$field = $extra_data->$field;
388 notify("Failed to load question options from the table $question_extension_table for questionid " .
394 $extra_answer_fields = $this->extra_answer_fields();
395 if (is_array($extra_answer_fields)) {
396 $answer_extension_table = array_shift($extra_answer_fields);
397 $question->options
->answers
= get_records_sql('
398 SELECT qa.*, qax.' . implode(', qax.', $extra_answer_fields) . '
399 FROM ' . $CFG->prefix
. 'question_answers qa, ' . $CFG->prefix
. '$answer_extension_table qax
400 WHERE qa.questionid = ' . $question->id
. ' AND qax.answerid = qa.id');
401 if (!$question->options
->answers
) {
402 notify("Failed to load question answers from the table $answer_extension_table for questionid " .
407 // Don't check for success or failure because some question types do not use the answers table.
408 $question->options
->answers
= get_records('question_answers', 'question', $question->id
, 'id ASC');
415 * Deletes states from the question-type specific tables
417 * @param string $stateslist Comma separated list of state ids to be deleted
419 function delete_states($stateslist) {
420 /// The default question type does not have any tables of its own
421 // therefore there is nothing to delete
427 * Deletes a question from the question-type specific tables
429 * @return boolean Success/Failure
430 * @param object $question The question being deleted
432 function delete_question($questionid) {
436 $extra_question_fields = $this->extra_question_fields();
437 if (is_array($extra_question_fields)) {
438 $question_extension_table = array_shift($extra_question_fields);
439 $success = $success && delete_records($question_extension_table, 'questionid', $questionid);
442 $extra_answer_fields = $this->extra_answer_fields();
443 if (is_array($extra_answer_fields)) {
444 $answer_extension_table = array_shift($extra_answer_fields);
445 $success = $success && delete_records_select($answer_extension_table,
446 "answerid IN (SELECT qa.id FROM {$CFG->prefix}question_answers qa WHERE qa.question = $questionid)");
449 $success = $success && delete_records('question_answers', 'question', $questionid);
455 * Returns the number of question numbers which are used by the question
457 * This function returns the number of question numbers to be assigned
458 * to the question. Most question types will have length one; they will be
459 * assigned one number. The 'description' type, however does not use up a
460 * number and so has a length of zero. Other question types may wish to
461 * handle a bundle of questions and hence return a number greater than one.
462 * @return integer The number of question numbers which should be
463 * assigned to the question.
464 * @param object $question The question whose length is to be determined.
465 * Question type specific information is included.
467 function actual_number_of_questions($question) {
468 // By default, each question is given one number
473 * Creates empty session and response information for the question
475 * This function is called to start a question session. Empty question type
476 * specific session data (if any) and empty response data will be added to the
477 * state object. Session data is any data which must persist throughout the
478 * attempt possibly with updates as the user interacts with the
479 * question. This function does NOT create new entries in the database for
480 * the session; a call to the {@link save_session_and_responses} member will
482 * @return bool Indicates success or failure.
483 * @param object $question The question for which the session is to be
484 * created. Question type specific information is
486 * @param object $state The state to create the session for. Note that
487 * this will not have been saved in the database so
488 * there will be no id. This object will be updated
489 * to include the question type specific information
490 * (it is passed by reference). In particular, empty
491 * responses will be created in the ->responses
493 * @param object $cmoptions
494 * @param object $attempt The attempt for which the session is to be
495 * started. Questions may wish to initialize the
496 * session in different ways depending on the user id
497 * or time available for the attempt.
499 function create_session_and_responses(&$question, &$state, $cmoptions, $attempt) {
500 // The default implementation should work for the legacy question types.
501 // Most question types with only a single form field for the student's response
502 // will use the empty string '' as the index for that one response. This will
503 // automatically be stored in and restored from the answer field in the
504 // question_states table.
505 $state->responses
= array(
512 * Restores the session data and most recent responses for the given state
514 * This function loads any session data associated with the question
515 * session in the given state from the database into the state object.
516 * In particular it loads the responses that have been saved for the given
517 * state into the ->responses member of the state object.
519 * Question types with only a single form field for the student's response
520 * will not need not restore the responses; the value of the answer
521 * field in the question_states table is restored to ->responses['']
522 * before this function is called. Question types with more response fields
523 * should override this method and set the ->responses field to an
524 * associative array of responses.
525 * @return bool Indicates success or failure.
526 * @param object $question The question object for the question including any
527 * question type specific information.
528 * @param object $state The saved state to load the session for. This
529 * object should be updated to include the question
530 * type specific session information and responses
531 * (it is passed by reference).
533 function restore_session_and_responses(&$question, &$state) {
534 // The default implementation does nothing (successfully)
539 * Saves the session data and responses for the given question and state
541 * This function saves the question type specific session data from the
542 * state object to the database. In particular for most question types it saves the
543 * responses from the ->responses member of the state object. The question type
544 * non-specific data for the state has already been saved in the question_states
545 * table and the state object contains the corresponding id and
546 * sequence number which may be used to index a question type specific table.
548 * Question types with only a single form field for the student's response
549 * which is contained in ->responses[''] will not have to save this response,
550 * it will already have been saved to the answer field of the question_states table.
551 * Question types with more response fields should override this method and save
552 * the responses in their own database tables.
553 * @return bool Indicates success or failure.
554 * @param object $question The question object for the question including
555 * the question type specific information.
556 * @param object $state The state for which the question type specific
557 * data and responses should be saved.
559 function save_session_and_responses(&$question, &$state) {
560 // The default implementation does nothing (successfully)
565 * Returns an array of values which will give full marks if graded as
566 * the $state->responses field
568 * The correct answer to the question in the given state, or an example of
569 * a correct answer if there are many, is returned. This is used by some question
570 * types in the {@link grade_responses()} function but it is also used by the
571 * question preview screen to fill in correct responses.
572 * @return mixed A response array giving the responses corresponding
573 * to the (or a) correct answer to the question. If there is
574 * no correct answer that scores 100% then null is returned.
575 * @param object $question The question for which the correct answer is to
576 * be retrieved. Question type specific information is
578 * @param object $state The state of the question, for which a correct answer is
579 * needed. Question type specific information is included.
581 function get_correct_responses(&$question, &$state) {
582 /* The default implementation returns the response for the first answer
583 that gives full marks. */
584 if ($question->options
->answers
) {
585 foreach ($question->options
->answers
as $answer) {
586 if (((int) $answer->fraction
) === 1) {
587 return array('' => addslashes($answer->answer
));
595 * Return an array of values with the texts for all possible responses stored
598 * All answers are found and their text values isolated
599 * @return object A mixed object
600 * ->id question id. Needed to manage random questions:
601 * it's the id of the actual question presented to user in a given attempt
602 * ->responses An array of values giving the responses corresponding
603 * to all answers to the question. Answer ids are used as keys.
604 * The text and partial credit are the object components
605 * @param object $question The question for which the answers are to
606 * be retrieved. Question type specific information is
610 function get_all_responses(&$question, &$state) {
611 if (isset($question->options
->answers
) && is_array($question->options
->answers
)) {
613 foreach ($question->options
->answers
as $aid=>$answer) {
615 $r->answer
= $answer->answer
;
616 $r->credit
= $answer->fraction
;
619 $result = new stdClass
;
620 $result->id
= $question->id
;
621 $result->responses
= $answers;
629 * Return the actual response to the question in a given state
632 * @return mixed An array containing the response or reponses (multiple answer, match)
633 * given by the user in a particular attempt.
634 * @param object $question The question for which the correct answer is to
635 * be retrieved. Question type specific information is
637 * @param object $state The state object that corresponds to the question,
638 * for which a correct answer is needed. Question
639 * type specific information is included.
642 function get_actual_response($question, $state) {
643 // change length to truncate responses here if you want
645 if (!empty($state->responses
)) {
646 $responses[] = (strlen($state->responses
['']) > $lmax) ?
647 substr($state->responses
[''], 0, $lmax).'...' : $state->responses
[''];
655 function get_fractional_grade(&$question, &$state) {
656 $maxgrade = $question->maxgrade
;
657 $grade = $state->grade
;
659 return (float)($grade/$maxgrade);
661 return (float)$grade;
667 * Checks if the response given is correct and returns the id
669 * @return int The ide number for the stored answer that matches the response
670 * given by the user in a particular attempt.
671 * @param object $question The question for which the correct answer is to
672 * be retrieved. Question type specific information is
674 * @param object $state The state object that corresponds to the question,
675 * for which a correct answer is needed. Question
676 * type specific information is included.
679 function check_response(&$question, &$state){
684 * If this question type requires extra CSS or JavaScript to function,
685 * then this method will return an array of <link ...> tags that reference
686 * those stylesheets. This function will also call require_js()
687 * from ajaxlib.php, to get any necessary JavaScript linked in too.
689 * The two parameters match the first two parameters of print_question.
691 * @param object $question The question object.
692 * @param object $state The state object.
694 * @return an array of bits of HTML to add to the head of pages where
695 * this question is print_question-ed in the body. The array should use
696 * integer array keys, which have no significance.
698 function get_html_head_contributions(&$question, &$state) {
699 // By default, we link to any of the files styles.css, styles.php,
700 // script.js or script.php that exist in the plugin folder.
701 // Core question types should not use this mechanism. Their styles
702 // should be included in the standard theme.
704 // We only do this once
705 // for this question type, no matter how often this method is called.
706 static $already_done = false;
710 $already_done = true;
712 $plugindir = $this->plugin_dir();
713 $baseurl = $this->plugin_baseurl();
714 $stylesheets = array();
715 if (file_exists($plugindir . '/styles.css')) {
716 $stylesheets[] = 'styles.css';
718 if (file_exists($plugindir . '/styles.php')) {
719 $stylesheets[] = 'styles.php';
721 if (file_exists($plugindir . '/script.js')) {
722 require_js($baseurl . '/script.js');
724 if (file_exists($plugindir . '/script.php')) {
725 require_js($baseurl . '/script.php');
727 $contributions = array();
728 foreach ($stylesheets as $stylesheet) {
729 $contributions[] = '<link rel="stylesheet" type="text/css" href="' .
730 $baseurl . '/' . $stylesheet . '" />"';
732 return $contributions;
736 * Prints the question including the number, grading details, content,
737 * feedback and interactions
739 * This function prints the question including the question number,
740 * grading details, content for the question, any feedback for the previously
741 * submitted responses and the interactions. The default implementation calls
742 * various other methods to print each of these parts and most question types
743 * will just override those methods.
744 * @param object $question The question to be rendered. Question type
745 * specific information is included. The
746 * maximum possible grade is in ->maxgrade. The name
747 * prefix for any named elements is in ->name_prefix.
748 * @param object $state The state to render the question in. The grading
749 * information is in ->grade, ->raw_grade and
750 * ->penalty. The current responses are in
751 * ->responses. This is an associative array (or the
752 * empty string or null in the case of no responses
753 * submitted). The last graded state is in
754 * ->last_graded (hence the most recently graded
755 * responses are in ->last_graded->responses). The
756 * question type specific information is also
758 * @param integer $number The number for this question.
759 * @param object $cmoptions
760 * @param object $options An object describing the rendering options.
762 function print_question(&$question, &$state, $number, $cmoptions, $options) {
763 /* The default implementation should work for most question types
764 provided the member functions it calls are overridden where required.
765 The layout is determined by the template question.html */
768 $isgraded = question_state_is_graded($state->last_graded
);
770 // If this question is being shown in the context of a quiz
771 // get the context so we can determine whether some extra links
772 // should be shown. (Don't show these links during question preview.)
773 $cm = get_coursemodule_from_instance('quiz', $cmoptions->id
);
774 if (!empty($cm->id
)) {
775 $context = get_context_instance(CONTEXT_MODULE
, $cm->id
);
776 } else if (!empty($cm->course
)) {
777 $context = get_context_instance(CONTEXT_COURSE
, $cm->course
);
779 $context = get_context_instance(CONTEXT_SYSTEM
, SITEID
);
782 // For editing teachers print a link to an editing popup window
784 if ($context && has_capability('moodle/question:manage', $context)) {
785 $stredit = get_string('edit');
786 $linktext = '<img src="'.$CFG->pixpath
.'/t/edit.gif" alt="'.$stredit.'" />';
787 $editlink = link_to_popup_window('/question/question.php?inpopup=1&id='.$question->id
, 'editquestion', $linktext, 450, 550, $stredit, '', true);
790 $generalfeedback = '';
791 if ($isgraded && $options->generalfeedback
) {
792 $generalfeedback = $this->format_text($question->generalfeedback
,
793 $question->questiontextformat
, $cmoptions);
797 if ($question->maxgrade
and $options->scores
) {
798 if ($cmoptions->optionflags
& QUESTION_ADAPTIVE
) {
799 $grade = !$isgraded ?
'--/' : round($state->last_graded
->grade
, $cmoptions->decimalpoints
).'/';
801 $grade .= $question->maxgrade
;
804 $comment = stripslashes($state->manualcomment
);
807 if (isset($options->questioncommentlink
) && $context && has_capability('mod/quiz:grade', $context)) {
808 $strcomment = get_string('commentorgrade', 'quiz');
809 $commentlink = '<div class="commentlink">'.link_to_popup_window ($options->questioncommentlink
.'?attempt='.$state->attempt
.'&question='.$question->id
,
810 'commentquestion', $strcomment, 450, 650, $strcomment, 'none', true).'</div>';
813 $history = $this->history($question, $state, $number, $cmoptions, $options);
815 include "$CFG->dirroot/question/type/question.html";
819 * Print history of responses
821 * Used by print_question()
823 function history($question, $state, $number, $cmoptions, $options) {
825 if(isset($options->history
) and $options->history
) {
826 if ($options->history
== 'all') {
828 $states = get_records_select('question_states', "attempt = '$state->attempt' AND question = '$question->id' AND event > '0'", 'seq_number ASC');
830 // show only graded states
831 $states = get_records_select('question_states', "attempt = '$state->attempt' AND question = '$question->id' AND event IN (".QUESTION_EVENTGRADE
.','.QUESTION_EVENTCLOSEANDGRADE
.")", 'seq_number ASC');
833 if (count($states) > 1) {
834 $strreviewquestion = get_string('reviewresponse', 'quiz');
835 $table = new stdClass
;
836 $table->width
= '100%';
837 if ($options->scores
) {
838 $table->head
= array (
839 get_string('numberabbr', 'quiz'),
840 get_string('action', 'quiz'),
841 get_string('response', 'quiz'),
843 get_string('score', 'quiz'),
844 //get_string('penalty', 'quiz'),
845 get_string('grade', 'quiz'),
848 $table->head
= array (
849 get_string('numberabbr', 'quiz'),
850 get_string('action', 'quiz'),
851 get_string('response', 'quiz'),
856 foreach ($states as $st) {
857 $st->responses
[''] = $st->answer
;
858 $this->restore_session_and_responses($question, $st);
859 $b = ($state->id
== $st->id
) ?
'<b>' : '';
860 $be = ($state->id
== $st->id
) ?
'</b>' : '';
861 if ($state->id
== $st->id
) {
862 $link = '<b>'.$st->seq_number
.'</b>';
864 if(isset($options->questionreviewlink
)) {
865 $link = link_to_popup_window ($options->questionreviewlink
.'?state='.$st->id
.'&number='.$number,
866 'reviewquestion', $st->seq_number
, 450, 650, $strreviewquestion, 'none', true);
868 $link = $st->seq_number
;
871 if ($options->scores
) {
872 $table->data
[] = array (
874 $b.get_string('event'.$st->event
, 'quiz').$be,
875 $b.$this->response_summary($question, $st).$be,
876 $b.userdate($st->timestamp
, get_string('timestr', 'quiz')).$be,
877 $b.round($st->raw_grade
, $cmoptions->decimalpoints
).$be,
878 //$b.round($st->penalty, $cmoptions->decimalpoints).$be,
879 $b.round($st->grade
, $cmoptions->decimalpoints
).$be
882 $table->data
[] = array (
884 $b.get_string('event'.$st->event
, 'quiz').$be,
885 $b.$this->response_summary($question, $st).$be,
886 $b.userdate($st->timestamp
, get_string('timestr', 'quiz')).$be,
890 $history = make_table($table);
898 * Prints the score obtained and maximum score available plus any penalty
901 * This function prints a summary of the scoring in the most recently
902 * graded state (the question may not have been submitted for marking at
903 * the current state). The default implementation should be suitable for most
905 * @param object $question The question for which the grading details are
906 * to be rendered. Question type specific information
907 * is included. The maximum possible grade is in
909 * @param object $state The state. In particular the grading information
910 * is in ->grade, ->raw_grade and ->penalty.
911 * @param object $cmoptions
912 * @param object $options An object describing the rendering options.
914 function print_question_grading_details(&$question, &$state, $cmoptions, $options) {
915 /* The default implementation prints the number of marks if no attempt
916 has been made. Otherwise it displays the grade obtained out of the
917 maximum grade available and a warning if a penalty was applied for the
918 attempt and displays the overall grade obtained counting all previous
919 responses (and penalties) */
921 if (QUESTION_EVENTDUPLICATE
== $state->event
) {
923 print_string('duplicateresponse', 'quiz');
925 if (!empty($question->maxgrade
) && $options->scores
) {
926 if (question_state_is_graded($state->last_graded
)) {
927 // Display the grading details from the last graded state
928 $grade = new stdClass
;
929 $grade->cur
= round($state->last_graded
->grade
, $cmoptions->decimalpoints
);
930 $grade->max
= $question->maxgrade
;
931 $grade->raw
= round($state->last_graded
->raw_grade
, $cmoptions->decimalpoints
);
933 // let student know wether the answer was correct
934 echo '<div class="correctness ';
935 if ($state->last_graded
->raw_grade
>= $question->maxgrade
/1.01) { // We divide by 1.01 so that rounding errors dont matter.
937 print_string('correct', 'quiz');
938 } else if ($state->last_graded
->raw_grade
> 0) {
939 echo ' partiallycorrect">';
940 print_string('partiallycorrect', 'quiz');
943 print_string('incorrect', 'quiz');
947 echo '<div class="gradingdetails">';
948 // print grade for this submission
949 print_string('gradingdetails', 'quiz', $grade);
950 if ($cmoptions->penaltyscheme
) {
951 // print details of grade adjustment due to penalties
952 if ($state->last_graded
->raw_grade
> $state->last_graded
->grade
){
954 print_string('gradingdetailsadjustment', 'quiz', $grade);
956 // print info about new penalty
957 // penalty is relevant only if the answer is not correct and further attempts are possible
958 if (($state->last_graded
->raw_grade
< $question->maxgrade
/ 1.01)
959 and (QUESTION_EVENTCLOSEANDGRADE
!== $state->event
)) {
961 if ('' !== $state->last_graded
->penalty
&& ((float)$state->last_graded
->penalty
) > 0.0) {
962 // A penalty was applied so display it
964 print_string('gradingdetailspenalty', 'quiz', $state->last_graded
->penalty
);
966 /* No penalty was applied even though the answer was
967 not correct (eg. a syntax error) so tell the student
968 that they were not penalised for the attempt */
970 print_string('gradingdetailszeropenalty', 'quiz');
980 * Prints the main content of the question including any interactions
982 * This function prints the main content of the question including the
983 * interactions for the question in the state given. The last graded responses
984 * are printed or indicated and the current responses are selected or filled in.
985 * Any names (eg. for any form elements) are prefixed with $question->name_prefix.
986 * This method is called from the print_question method.
987 * @param object $question The question to be rendered. Question type
988 * specific information is included. The name
989 * prefix for any named elements is in ->name_prefix.
990 * @param object $state The state to render the question in. The grading
991 * information is in ->grade, ->raw_grade and
992 * ->penalty. The current responses are in
993 * ->responses. This is an associative array (or the
994 * empty string or null in the case of no responses
995 * submitted). The last graded state is in
996 * ->last_graded (hence the most recently graded
997 * responses are in ->last_graded->responses). The
998 * question type specific information is also
1000 * The state is passed by reference because some adaptive
1001 * questions may want to update it during rendering
1002 * @param object $cmoptions
1003 * @param object $options An object describing the rendering options.
1005 function print_question_formulation_and_controls(&$question, &$state, $cmoptions, $options) {
1006 /* This default implementation prints an error and must be overridden
1007 by all question type implementations, unless the default implementation
1008 of print_question has been overridden. */
1010 notify('Error: Question formulation and input controls has not'
1011 .' been implemented for question type '.$this->name());
1015 * Prints the submit button(s) for the question in the given state
1017 * This function prints the submit button(s) for the question in the
1018 * given state. The name of any button created will be prefixed with the
1019 * unique prefix for the question in $question->name_prefix. The suffix
1020 * 'submit' is reserved for the single question submit button and the suffix
1021 * 'validate' is reserved for the single question validate button (for
1022 * question types which support it). Other suffixes will result in a response
1023 * of that name in $state->responses which the printing and grading methods
1025 * @param object $question The question for which the submit button(s) are to
1026 * be rendered. Question type specific information is
1027 * included. The name prefix for any
1028 * named elements is in ->name_prefix.
1029 * @param object $state The state to render the buttons for. The
1030 * question type specific information is also
1032 * @param object $cmoptions
1033 * @param object $options An object describing the rendering options.
1035 function print_question_submit_buttons(&$question, &$state, $cmoptions, $options) {
1036 /* The default implementation should be suitable for most question
1037 types. It prints a mark button in the case where individual marking is
1040 if (($cmoptions->optionflags
& QUESTION_ADAPTIVE
) and !$options->readonly
) {
1041 echo '<input type="submit" name="';
1042 echo $question->name_prefix
;
1043 echo 'submit" value="';
1044 print_string('mark', 'quiz');
1045 echo '" class="submit btn"';
1052 * Return a summary of the student response
1054 * This function returns a short string of no more than a given length that
1055 * summarizes the student's response in the given $state. This is used for
1056 * example in the response history table
1057 * @return string The summary of the student response
1058 * @param object $question
1059 * @param object $state The state whose responses are to be summarized
1060 * @param int $length The maximum length of the returned string
1062 function response_summary($question, $state, $length=80) {
1063 // This should almost certainly be overridden
1064 $responses = $this->get_actual_response($question, $state);
1065 if (empty($responses) ||
!is_array($responses)) {
1066 $responses = array();
1068 if (is_array($responses)) {
1069 $responses = implode(',', $responses);
1071 return substr($responses, 0, $length);
1075 * Renders the question for printing and returns the LaTeX source produced
1077 * This function should render the question suitable for a printed problem
1078 * or solution sheet in LaTeX and return the rendered output.
1079 * @return string The LaTeX output.
1080 * @param object $question The question to be rendered. Question type
1081 * specific information is included.
1082 * @param object $state The state to render the question in. The
1083 * question type specific information is also
1085 * @param object $cmoptions
1086 * @param string $type Indicates if the question or the solution is to be
1087 * rendered with the values 'question' and
1090 function get_texsource(&$question, &$state, $cmoptions, $type) {
1091 // The default implementation simply returns a string stating that
1092 // the question is only available online.
1094 return get_string('onlineonly', 'texsheet');
1098 * Compares two question states for equivalence of the student's responses
1100 * The responses for the two states must be examined to see if they represent
1101 * equivalent answers to the question by the student. This method will be
1102 * invoked for each of the previous states of the question before grading
1103 * occurs. If the student is found to have already attempted the question
1104 * with equivalent responses then the attempt at the question is ignored;
1105 * grading does not occur and the state does not change. Thus they are not
1106 * penalized for this case.
1108 * @param object $question The question for which the states are to be
1109 * compared. Question type specific information is
1111 * @param object $state The state of the question. The responses are in
1112 * ->responses. This is the only field of $state
1113 * that it is safe to use.
1114 * @param object $teststate The state whose responses are to be
1115 * compared. The state will be of the same age or
1116 * older than $state. If possible, the method should
1117 * only use the field $teststate->responses, however
1118 * any field that is set up by restore_session_and_responses
1121 function compare_responses(&$question, $state, $teststate) {
1122 // The default implementation performs a comparison of the response
1123 // arrays. The ordering of the arrays does not matter.
1124 // Question types may wish to override this (eg. to ignore trailing
1125 // white space or to make "7.0" and "7" compare equal).
1127 return $state->responses
=== $teststate->responses
;
1131 * Checks whether a response matches a given answer
1133 * This method only applies to questions that use teacher-defined answers
1137 function test_response(&$question, &$state, $answer) {
1138 $response = isset($state->responses
['']) ?
$state->responses
[''] : '';
1139 return ($response == $answer->answer
);
1143 * Performs response processing and grading
1145 * This function performs response processing and grading and updates
1146 * the state accordingly.
1147 * @return boolean Indicates success or failure.
1148 * @param object $question The question to be graded. Question type
1149 * specific information is included.
1150 * @param object $state The state of the question to grade. The current
1151 * responses are in ->responses. The last graded state
1152 * is in ->last_graded (hence the most recently graded
1153 * responses are in ->last_graded->responses). The
1154 * question type specific information is also
1155 * included. The ->raw_grade and ->penalty fields
1156 * must be updated. The method is able to
1157 * close the question session (preventing any further
1158 * attempts at this question) by setting
1159 * $state->event to QUESTION_EVENTCLOSEANDGRADE
1160 * @param object $cmoptions
1162 function grade_responses(&$question, &$state, $cmoptions) {
1163 // The default implementation uses the test_response method to
1164 // compare what the student entered against each of the possible
1165 // answers stored in the question, and uses the grade from the
1166 // first one that matches. It also sets the marks and penalty.
1167 // This should be good enought for most simple question types.
1169 $state->raw_grade
= 0;
1170 foreach($question->options
->answers
as $answer) {
1171 if($this->test_response($question, $state, $answer)) {
1172 $state->raw_grade
= $answer->fraction
;
1177 // Make sure we don't assign negative or too high marks.
1178 $state->raw_grade
= min(max((float) $state->raw_grade
,
1179 0.0), 1.0) * $question->maxgrade
;
1181 // Update the penalty.
1182 $state->penalty
= $question->penalty
* $question->maxgrade
;
1184 // mark the state as graded
1185 $state->event
= ($state->event
== QUESTION_EVENTCLOSE
) ? QUESTION_EVENTCLOSEANDGRADE
: QUESTION_EVENTGRADE
;
1192 * Includes configuration settings for the question type on the quiz admin
1195 * TODO: It makes no sense any longer to do the admin for question types
1196 * from the quiz admin page. This should be changed.
1197 * Returns an array of objects describing the options for the question type
1198 * to be included on the quiz module admin page.
1199 * Configuration options can be included by setting the following fields in
1201 * ->name The name of the option within this question type.
1202 * The full option name will be constructed as
1203 * "quiz_{$this->name()}_$name", the human readable name
1204 * will be displayed with get_string($name, 'quiz').
1205 * ->code The code to display the form element, help button, etc.
1206 * i.e. the content for the central table cell. Be sure
1207 * to name the element "quiz_{$this->name()}_$name" and
1208 * set the value to $CFG->{"quiz_{$this->name()}_$name"}.
1209 * ->help Name of the string from the quiz module language file
1210 * to be used for the help message in the third column of
1211 * the table. An empty string (or the field not set)
1212 * means to leave the box empty.
1213 * Links to custom settings pages can be included by setting the following
1214 * fields in the object:
1215 * ->name The name of the link text string.
1216 * get_string($name, 'quiz') will be called.
1217 * ->link The filename part of the URL for the link. The full URL
1219 * "$CFG->wwwroot/question/type/{$this->name()}/$link?sesskey=$sesskey"
1220 * [but with the relavant calls to the s and rawurlencode
1221 * functions] where $sesskey is the sesskey for the user.
1222 * @return array Array of objects describing the configuration options to
1223 * be included on the quiz module admin page.
1225 function get_config_options() {
1226 // No options by default
1232 * Returns true if the editing wizard is finished, false otherwise.
1234 * The default implementation returns true, which is suitable for all question-
1235 * types that only use one editing form. This function is used in
1236 * question.php to decide whether we can regrade any states of the edited
1237 * question and redirect to edit.php.
1239 * The dataset dependent question-type, which is extended by the calculated
1240 * question-type, overwrites this method because it uses multiple pages (i.e.
1241 * a wizard) to set up the question and associated datasets.
1243 * @param object $form The data submitted by the previous page.
1245 * @return boolean Whether the wizard's last page was submitted or not.
1247 function finished_edit_wizard(&$form) {
1248 //In the default case there is only one edit page.
1253 * Prints a table of course modules in which the question is used
1255 * TODO: This should be made quiz-independent
1257 * This function is used near the end of the question edit forms in all question types
1258 * It prints the table of quizzes in which the question is used
1259 * containing checkboxes to allow the teacher to replace the old question version
1261 * @param object $question
1262 * @param object $course
1263 * @param integer $cmid optional The id of the course module currently being edited
1265 function print_replacement_options($question, $course, $cmid='0') {
1267 // Disable until the versioning code has been fixed
1272 // no need to display replacement options if the question is new
1273 if(empty($question->id
)) {
1277 // get quizzes using the question (using the question_instances table)
1278 $quizlist = array();
1279 if(!$instances = get_records('quiz_question_instances', 'question', $question->id
)) {
1280 $instances = array();
1282 foreach($instances as $instance) {
1283 $quizlist[$instance->quiz
] = $instance->quiz
;
1285 $quizlist = implode(',', $quizlist);
1286 if(empty($quizlist) or !$quizzes = get_records_list('quiz', 'id', $quizlist)) {
1291 if(count($quizzes) > 0) {
1293 $strquizname = get_string('modulename', 'quiz');
1294 $strdoreplace = get_string('replace', 'quiz');
1295 $straffectedstudents = get_string('affectedstudents', 'quiz', $course->students
);
1296 echo "<tr valign=\"top\">\n";
1297 echo "<td align=\"right\"><b>".get_string("replacementoptions", "quiz").":</b></td>\n";
1298 echo "<td align=\"left\">\n";
1299 echo "<table cellpadding=\"5\" align=\"left\" class=\"generalbox\" width=\"100%\">\n";
1301 echo "<th align=\"left\" valign=\"top\" nowrap=\"nowrap\" class=\"generaltableheader c0\" scope=\"col\">$strquizname</th>\n";
1302 echo "<th align=\"center\" valign=\"top\" nowrap=\"nowrap\" class=\"generaltableheader c0\" scope=\"col\">$strdoreplace</th>\n";
1303 echo "<th align=\"left\" valign=\"top\" nowrap=\"nowrap\" class=\"generaltableheader c0\" scope=\"col\">$straffectedstudents</th>\n";
1305 foreach($quizzes as $quiz) {
1306 // work out whethere it should be checked by default
1308 if((int)$cmid === (int)$quiz->id
1309 or empty($quiz->usercount
)) {
1310 $checked = "checked=\"checked\"";
1313 // find how many different students have already attempted this quiz
1314 $students = array();
1315 if($attempts = get_records_select('quiz_attempts', "quiz = '$quiz->id' AND preview = '0'")) {
1316 foreach($attempts as $attempt) {
1317 if (record_exists('question_states', 'attempt', $attempt->uniqueid
, 'question', $question->id
, 'originalquestion', 0)) {
1318 $students[$attempt->userid
] = 1;
1322 $studentcount = count($students);
1324 $strstudents = $studentcount === 1 ?
$course->student
: $course->students
;
1326 echo "<td align=\"left\" class=\"generaltablecell c0\">".format_string($quiz->name
)."</td>\n";
1327 echo "<td align=\"center\" class=\"generaltablecell c0\"><input name=\"q{$quiz->id}replace\" type=\"checkbox\" ".$checked." /></td>\n";
1328 echo "<td align=\"left\" class=\"generaltablecell c0\">".(($studentcount) ?
$studentcount.' '.$strstudents : '-')."</td>\n";
1333 echo "</td></tr>\n";
1337 * Call format_text from weblib.php with the options appropriate to question types.
1339 * @param string $text the text to format.
1340 * @param integer $text the type of text. Normally $question->questiontextformat.
1341 * @param object $cmoptions the context the string is being displayed in. Only $cmoptions->course is used.
1342 * @return string the formatted text.
1344 function format_text($text, $textformat, $cmoptions = NULL) {
1345 $formatoptions = new stdClass
;
1346 $formatoptions->noclean
= true;
1347 $formatoptions->para
= false;
1348 return format_text($text, $textformat, $formatoptions, $cmoptions === NULL ?
NULL : $cmoptions->course
);
1351 /// BACKUP FUNCTIONS ////////////////////////////
1354 * Backup the data in the question
1356 * This is used in question/backuplib.php
1358 function backup($bf,$preferences,$question,$level=6) {
1359 // The default type has nothing to back up
1363 /// RESTORE FUNCTIONS /////////////////
1366 * Restores the data in the question
1368 * This is used in question/restorelib.php
1370 function restore($old_question_id,$new_question_id,$info,$restore) {
1371 // The default question type has nothing to restore
1375 function restore_map($old_question_id,$new_question_id,$info,$restore) {
1376 // There is nothing to decode
1380 function restore_recode_answer($state, $restore) {
1381 // There is nothing to decode
1382 return $state->answer
;