multichoice.classes.inc in Quiz 6.4
The main classes for the multichoice question type.
These inherit or implement code found in quiz_question.classes.inc.
Sponsored by: Norwegian Centre for Telemedicine Code: falcon
Based on: Other question types in the quiz framework.
Question type, enabling the creation of multiple choice and multiple answer questions.
File
question_types/multichoice/multichoice.classes.incView source
<?php
/**
* The main classes for the multichoice question type.
*
* These inherit or implement code found in quiz_question.classes.inc.
*
* Sponsored by: Norwegian Centre for Telemedicine
* Code: falcon
*
* Based on:
* Other question types in the quiz framework.
*
*
*
* @file
* Question type, enabling the creation of multiple choice and multiple answer questions.
*/
/**
* Extension of QuizQuestion.
*/
class MultichoiceQuestion extends QuizQuestion {
/**
* Forgive some possible logical flaws in the user input.
*/
private function forgive() {
if ($this->node->choice_multi == 1) {
for ($i = 0; isset($this->node->alternatives[$i]); $i++) {
$short =& $this->node->alternatives[$i];
// If the scoring data doesn't make sense, use the data from the "correct" checkbox to set the score data
if ($short['score_if_chosen'] == $short['score_if_not_chosen'] || !is_numeric($short['score_if_chosen']) || !is_numeric($short['score_if_not_chosen'])) {
if ($short['correct'] == 1) {
$short['score_if_chosen'] = 1;
$short['score_if_not_chosen'] = 0;
}
else {
if (variable_get('multichoice_def_scoring', 0) == 0) {
$short['score_if_chosen'] = -1;
$short['score_if_not_chosen'] = 0;
}
elseif (variable_get('multichoice_def_scoring', 0) == 1) {
$short['score_if_chosen'] = 0;
$short['score_if_not_chosen'] = 1;
}
}
}
}
}
else {
// For questions with one, and only one, correct answer, there will be no points awarded for alternatives
// not chosen.
for ($i = 0; isset($this->node->alternatives[$i]); $i++) {
$short =& $this->node->alternatives[$i];
$short['score_if_not_chosen'] = 0;
if ($short['correct'] == 1 && !_quiz_is_int($short['score_if_chosen'], 1)) {
$short['score_if_chosen'] = 1;
}
}
}
}
/**
* Warn the user about possible user errors
*/
private function warn() {
// Count the number of correct answers
$num_corrects = 0;
for ($i = 0; isset($this->node->alternatives[$i]); $i++) {
$alt =& $this->node->alternatives[$i];
if ($alt['score_if_chosen'] > $alt['score_if_not_chosen']) {
$num_corrects++;
}
}
if ($num_corrects == 1 && $this->node->choice_multi == 1 || $num_corrects > 1 && $this->node->choice_multi == 0) {
$link_options = array();
if (isset($_GET['destination'])) {
$link_options['query'] = array(
'destination' => $_GET['destination'],
);
}
$go_back = l(t('go back'), 'node/' . $this->node->nid . '/edit', $link_options);
if ($num_corrects == 1) {
drupal_set_message(t('Your question allows multiple answers. Only one of the alternatives have been marked as correct. If this wasn\'t intended please !go_back and correct it.', array(
'!go_back' => $go_back,
)), 'warning');
}
else {
drupal_set_message(t('Your question doesn\'t allow multiple answers. More than one of the alternatives have been marked as correct. If this wasn\'t intended please !go_back and correct it.', array(
'!go_back' => $go_back,
)), 'warning');
}
}
}
/**
* Run check_markup() on the field of the specified choice alternative
* @param $alternativeIndex
* The index of the alternative in the alternatives array.
* @param $field
* The name of the field we want to check markup on
* @param $check_user_access
* Whether or not to check for user access to the filter we're trying to apply
* @return HTML markup
*/
private function checkMarkup($alternativeIndex, $field, $check_user_access = FALSE) {
$alternative = $this->node->alternatives[$alternativeIndex];
return check_markup($alternative[$field], $alternative[$field . '_format'], $check_user_access);
}
/**
* Implementation of save
*
* Stores the question in the database.
*
* @param is_new if - if the node is a new node...
* (non-PHPdoc)
* @see sites/all/modules/quiz-HEAD/question_types/quiz_question/QuizQuestion#save()
*/
public function saveNodeProperties($is_new = FALSE) {
$is_new = $is_new || $this->node->revision == 1;
// Before we save we forgive some possible user errors
$this
->forgive();
// We also add warnings on other possible user errors
$this
->warn();
if ($is_new) {
$sql = 'INSERT INTO {quiz_multichoice_properties}
(nid, vid, choice_multi, choice_random, choice_boolean)
VALUES (%d, %d, %d, %d, %d)';
db_query($sql, $this->node->nid, $this->node->vid, $this->node->choice_multi, $this->node->choice_random, $this->node->choice_boolean);
for ($i = 0; isset($this->node->alternatives[$i]); $i++) {
if (drupal_strlen($this->node->alternatives[$i]['answer']) > 0) {
$this
->insertAlternative($i);
}
}
}
else {
$sql = 'UPDATE {quiz_multichoice_properties}
SET choice_multi = %d, choice_random = %d, choice_boolean = %d
WHERE nid = %d AND vid = %d';
db_query($sql, $this->node->choice_multi, $this->node->choice_random, $this->node->choice_boolean, $this->node->nid, $this->node->vid);
// We fetch ids for the existing answers belonging to this question
// We need to figure out if an existing alternative has been changed or deleted.
$sql = 'SELECT id FROM {quiz_multichoice_answers}
WHERE question_nid = %d AND question_vid = %d';
$res = db_query($sql, $this->node->nid, $this->node->vid);
// We start by assuming that all existing alternatives needs to be deleted
$ids_to_delete = array();
while ($res_o = db_fetch_object($res)) {
$ids_to_delete[] = $res_o->id;
}
for ($i = 0; isset($this->node->alternatives[$i]); $i++) {
$short = $this->node->alternatives[$i];
if (drupal_strlen($this->node->alternatives[$i]['answer']) > 0) {
// If new alternative
if (!is_numeric($short['id'])) {
$this
->insertAlternative($i);
}
else {
$this
->updateAlternative($i);
// Make sure this alternative isn't deleted
$key = array_search($short['id'], $ids_to_delete);
$ids_to_delete[$key] = FALSE;
}
}
}
foreach ($ids_to_delete as $id_to_delete) {
if ($id_to_delete) {
db_query('DELETE FROM {quiz_multichoice_answers} WHERE id = %d', $id_to_delete);
}
}
}
$this
->saveUserSettings();
}
/**
* Helper function. Saves new alternatives
*
* @param $i
* The alternative index
*/
private function insertAlternative($i) {
$sql = 'INSERT INTO {quiz_multichoice_answers}
(answer, answer_format, feedback_if_chosen, feedback_if_chosen_format,
feedback_if_not_chosen, feedback_if_not_chosen_format, score_if_chosen,
score_if_not_chosen, question_nid, question_vid)
VALUES(\'%s\', %d, \'%s\', %d, \'%s\', %d, %d, %d, %d, %d)';
$short = $this->node->alternatives[$i];
db_query($sql, $short['answer'], $short['answer_format'], $short['feedback_if_chosen'], $short['feedback_if_chosen_format'], $short['feedback_if_not_chosen'], $short['feedback_if_not_chosen_format'], $short['score_if_chosen'], $short['score_if_not_chosen'], $this->node->nid, $this->node->vid);
}
/**
* Helper function. Updates existing alternatives
*
* @param $i
* The alternative index
*/
private function updateAlternative($i) {
$sql = 'UPDATE {quiz_multichoice_answers}
SET answer = \'%s\', answer_format = %d, feedback_if_chosen = \'%s\',
feedback_if_chosen_format = %d, feedback_if_not_chosen = \'%s\',
feedback_if_not_chosen_format = %d, score_if_chosen = %d, score_if_not_chosen = %d
WHERE id = %d AND question_nid = %d AND question_vid = %d';
$short = $this->node->alternatives[$i];
db_query($sql, $short['answer'], $short['answer_format'], $short['feedback_if_chosen'], $short['feedback_if_chosen_format'], $short['feedback_if_not_chosen'], $short['feedback_if_not_chosen_format'], $short['score_if_chosen'], $short['score_if_not_chosen'], $short['id'], $this->node->nid, $this->node->vid);
}
/**
* Implementation of validate
*
* QuizQuestion#validate()
*/
public function validateNode(array &$form) {
if ($this->node->choice_multi == 0) {
$found_one_correct = FALSE;
for ($i = 0; is_array($this->node->alternatives[$i]); $i++) {
$short = $this->node->alternatives[$i];
if (drupal_strlen($this
->checkMarkup($i, 'answer')) < 1) {
continue;
}
if ($short['correct'] == 1) {
if ($found_one_correct) {
// We don't display an error message here since we allow alternatives to be partially correct
}
else {
$found_one_correct = TRUE;
}
}
}
if (!$found_one_correct) {
form_set_error('choice_multi', t('You have not marked any alternatives as correct. If there are no correct alternatives you should allow multiple answers.'));
}
}
else {
for ($i = 0; isset($this->node->alternatives[$i]); $i++) {
$short = $this->node->alternatives[$i];
if (strlen($this
->checkMarkup($i, 'answer')) < 1) {
continue;
}
if ($short['score_if_chosen'] < $short['score_if_not_chosen'] && $short['correct']) {
form_set_error("alternatives][{$i}][score_if_not_chosen", t('The alternative is marked as correct, but gives more points if you don\'t select it.'));
}
elseif ($short['score_if_chosen'] > $short['score_if_not_chosen'] && !$short['correct']) {
form_set_error("alternatives][{$i}][score_if_chosen", t('The alternative is not marked as correct, but gives more points if you select it.'));
}
}
}
}
/**
* Implementation of delete
*
* @see QuizQuestion#delete()
*/
public function delete($only_this_version = FALSE) {
$delete_properties = 'DELETE FROM {quiz_multichoice_properties} WHERE nid = %d';
$delete_answers = 'DELETE FROM {quiz_multichoice_answers} WHERE question_nid = %d';
$delete_multi_results = '
DELETE FROM {quiz_multichoice_user_answer_multi}
USING {quiz_multichoice_user_answer_multi}
INNER JOIN {quiz_multichoice_user_answers}
ON {quiz_multichoice_user_answer_multi}.user_answer_id = {quiz_multichoice_user_answers}.id
WHERE {quiz_multichoice_user_answers}.question_nid = %d' . ($only_this_version ? ' AND question_vid = %d' : '');
$delete_results = 'DELETE FROM {quiz_multichoice_user_answers} WHERE question_nid = %d';
if ($only_this_version) {
$delete_properties .= ' AND vid = %d';
$delete_answers .= ' AND question_vid = %d';
$delete_results .= ' AND question_vid = %d';
}
db_query($delete_properties, $this->node->nid, $this->node->vid);
db_query($delete_answers, $this->node->nid, $this->node->vid);
db_query($delete_multi_results, $this->node->nid, $this->node->vid);
db_query($delete_results, $this->node->nid, $this->node->vid);
parent::delete($only_this_version);
}
/**
* Implementation of getNodeProperties
*
* @see QuizQuestion#getNodeProperties()
*/
public function getNodeProperties() {
if (isset($this->nodeProperties)) {
return $this->nodeProperties;
}
$props = parent::getNodeProperties();
// Load the properties
$sql = 'SELECT choice_multi, choice_random, choice_boolean
FROM {quiz_multichoice_properties}
WHERE nid = %d AND vid = %d';
$res = db_query($sql, $this->node->nid, $this->node->vid);
$res_a = db_fetch_array($res);
if (is_array($res_a)) {
$props = array_merge($props, $res_a);
}
// Load the answers
$sql = 'SELECT id, answer, answer_format, feedback_if_chosen, feedback_if_chosen_format,
feedback_if_not_chosen, feedback_if_not_chosen_format, score_if_chosen, score_if_not_chosen
FROM {quiz_multichoice_answers}
WHERE question_nid = %d AND question_vid = %d
ORDER BY id';
$res = db_query($sql, $this->node->nid, $this->node->vid);
$props['alternatives'] = array();
// init array so it can be iterated even if empty
while ($res_arr = db_fetch_array($res)) {
$props['alternatives'][] = $res_arr;
}
$this->nodeProperties = $props;
return $props;
}
/**
* Implementation of getNodeView
*
* @see QuizQuestion#getNodeView()
*/
public function getNodeView() {
$content = parent::getNodeView();
if ($this->node->choice_random) {
$this
->shuffle($this->node->alternatives);
}
$content['answers'] = array(
'#value' => theme('multichoice_answer_node_view', $this->node->alternatives, $this
->viewCanRevealCorrect()),
'#weight' => 2,
);
return $content;
}
/**
* Generates the question form.
*
* This is called whenever a question is rendered, either
* to an administrator or to a quiz taker.
*/
public function getAnsweringForm(array $form_state = NULL, $rid) {
$form = parent::getAnsweringForm($form_state, $rid);
$form['#theme'] = 'multichoice_answering_form';
/* We use an array looking key to be able to store multiple answers in tries.
* At the moment all user answers have to be stored in tries. This is something we plan
* to fix in quiz 5.x.
*/
$form['tries[answer]'] = array(
'#options' => array(),
'#theme' => 'multichoice_alternative',
);
if (isset($rid)) {
// This question has already been answered. We load the answer.
$response = new MultichoiceResponse($rid, $this->node);
}
for ($i = 0; isset($this->node->alternatives[$i]); $i++) {
$short = $this->node->alternatives[$i];
$answer_markup = $this
->checkMarkup($i, 'answer', FALSE);
if (drupal_strlen($answer_markup) > 0) {
$form['tries[answer]']['#options'][$short['id']] = $answer_markup;
}
}
if ($this->node->choice_random) {
// We save the choice order so that the order will be the same in the answer report
$form['tries[choice_order]'] = array(
'#type' => 'hidden',
'#value' => implode(',', $this
->shuffle($form['tries[answer]']['#options'])),
);
}
if ($this->node->choice_multi) {
$form['tries[answer]']['#type'] = 'checkboxes';
$form['tries[answer]']['#title'] = t('Choose');
if (isset($response)) {
if (is_array($response
->getResponse())) {
$form['tries[answer]']['#default_value'] = $response
->getResponse();
}
}
}
else {
$form['tries[answer]']['#type'] = 'radios';
$form['tries[answer]']['#title'] = t('Choose one');
if (isset($response)) {
if (is_array($response
->getResponse())) {
$form['tries[answer]']['#default_value'] = array_pop($response
->getResponse());
}
}
}
return $form;
}
/**
* Custom shuffle function. It keeps the array key - value relationship intact
*
* @param array $array
* @return unknown_type
*/
private function shuffle(array &$array) {
$newArray = array();
$toReturn = array_keys($array);
shuffle($toReturn);
foreach ($toReturn as $key) {
$newArray[$key] = $array[$key];
}
$array = $newArray;
return $toReturn;
}
/**
* Implementation of getCreationForm
*
* @see QuizQuestion#getCreationForm()
*/
public function getCreationForm(array $form_state = NULL) {
$form = array();
$type = node_get_types('type', $this->node);
// We add #action to the form because of the use of ajax
$options = array();
$get = $_GET;
unset($get['q']);
if (!empty($get)) {
$options['query'] = $get;
}
$action = url('node/add/' . $type->type, $options);
if (isset($this->node->nid)) {
$action = url('node/' . $this->node->nid . '/edit', $options);
}
$form['#action'] = $action;
$form['alternatives'] = array(
'#type' => 'fieldset',
'#title' => t('Answer'),
'#collapsible' => TRUE,
'#collapsed' => FALSE,
'#weight' => -4,
'#tree' => TRUE,
);
// Get the nodes settings, users settings or default settings
$default_settings = $this
->getDefaultAltSettings();
$form['alternatives']['settings'] = array(
'#type' => 'fieldset',
'#title' => t('Settings'),
'#collapsible' => TRUE,
'#collapsed' => FALSE,
'#description' => t('Your settings will be remembered.'),
);
$form['alternatives']['settings']['choice_multi'] = array(
'#type' => 'checkbox',
'#title' => t('Multiple answers'),
'#description' => t('Allow any number of answers(checkboxes are used). If this box is not checked, one, and only one answer is allowed(radiobuttons are used).'),
'#default_value' => $default_settings['choice_multi'],
'#parents' => array(
'choice_multi',
),
);
$form['alternatives']['settings']['choice_random'] = array(
'#type' => 'checkbox',
'#title' => t('Random order'),
'#description' => t('Present alternatives in random order when quiz is beeing taken.'),
'#default_value' => $default_settings['choice_random'],
'#parents' => array(
'choice_random',
),
);
$form['alternatives']['settings']['choice_boolean'] = array(
'#type' => 'checkbox',
'#title' => t('Simple scoring'),
'#description' => t('Give max score if everything is correct. Zero points otherwise.'),
'#default_value' => $default_settings['choice_boolean'],
'#parents' => array(
'choice_boolean',
),
);
// Add helper tag where we will place the input selector for all the textareas.
$form['alternatives']['input_format_all'] = array(
'#type' => 'markup',
'#value' => '<DIV id="input-all-ph"></DIV>',
);
$form['alternatives']['#theme'][] = 'multichoice_creation_form';
$i = 0;
// choice_count might be stored in the form_state after an ajax callback
if (isset($form_state['choice_count'])) {
$choice_count = $form_state['choice_count'];
}
else {
$choice_count = max(variable_get('multichoice_def_num_of_alts', 2), isset($this->node->alternatives) ? count($this->node->alternatives) : 0);
}
for (; $i < $choice_count; $i++) {
$short = isset($this->node->alternatives[$i]) ? $this->node->alternatives[$i] : NULL;
$form['alternatives'][$i] = array(
'#type' => 'fieldset',
'#title' => t('Alternative !i', array(
'!i' => $i + 1,
)),
'#collapsible' => TRUE,
'#collapsed' => !($i < 2 || isset($short['answer'])),
);
$form['alternatives'][$i]['#theme'][] = 'multichoice_alternative_creation';
if (is_array($short)) {
if ($short['score_if_chosen'] == $short['score_if_not_chosen']) {
$correct_default = $short['correct'];
}
else {
$correct_default = $short['score_if_chosen'] > $short['score_if_not_chosen'];
}
}
else {
$correct_default = FALSE;
}
$form['alternatives'][$i]['correct'] = array(
'#type' => 'checkbox',
'#title' => t('Correct'),
'#default_value' => $correct_default,
'#attributes' => array(
'onchange' => 'refreshScores(this, ' . variable_get('multichoice_def_scoring', 0) . ')',
),
);
// We add id to be able to update the correct alternatives if the node is updated, without destroying
// existing answer reports
$form['alternatives'][$i]['id'] = array(
'#type' => 'value',
'#value' => $short['id'],
);
$form['alternatives'][$i]["answer"] = array(
'#type' => 'textarea',
'#title' => t('Alternative !i', array(
'!i' => $i + 1,
)),
'#default_value' => $short['answer'],
'#required' => $i < 2,
);
$form['alternatives'][$i]['format'] = filter_form($short['answer_format'], NULL, array(
'alternatives',
$i,
'answer_format',
));
$form['alternatives'][$i]['advanced'] = array(
'#type' => 'fieldset',
'#title' => t('Advanced options'),
'#collapsible' => TRUE,
'#collapsed' => TRUE,
);
$form['alternatives'][$i]['advanced']['feedback_if_chosen'] = array(
'#type' => 'textarea',
'#title' => t('Feedback if chosen'),
'#description' => t('This feedback is given to users who chooses this alternative.'),
'#parents' => array(
'alternatives',
$i,
'feedback_if_chosen',
),
'#default_value' => $short['feedback_if_chosen'],
);
$form['alternatives'][$i]['advanced']['format'] = filter_form($short['feedback_if_chosen_format'], NULL, array(
'alternatives',
$i,
'feedback_if_chosen_format',
));
// We add 'helper' to trick the current version of the wysiwyg module to add an editor to several
// textareas in the same fieldset
$form['alternatives'][$i]['advanced']['helper']['feedback_if_not_chosen'] = array(
'#type' => 'textarea',
'#title' => t('Feedback if not chosen'),
'#description' => t('This feedback is given to users who doesn\'t choose this alternative.'),
'#parents' => array(
'alternatives',
$i,
'feedback_if_not_chosen',
),
'#default_value' => $short['feedback_if_not_chosen'],
);
$form['alternatives'][$i]['advanced']['helper']['format'] = filter_form($short['feedback_if_not_chosen_format'], NULL, array(
'alternatives',
$i,
'feedback_if_not_chosen_format',
));
$default_value = isset($this->node->alternatives[$i]['score_if_chosen']) ? $this->node->alternatives[$i]['score_if_chosen'] : 0;
if (!isset($default_value)) {
$default_value = '0';
}
$form['alternatives'][$i]['advanced']['score_if_chosen'] = array(
'#type' => 'textfield',
'#title' => t('Score if chosen'),
'#size' => 4,
'#maxlength' => 4,
'#default_value' => $default_value,
'#description' => t('This score is added to the users total score if the user chooses this alternative.'),
'#attributes' => array(
'onkeypress' => 'refreshCorrect(this)',
'onkeyup' => 'refreshCorrect(this)',
'onchange' => 'refreshCorrect(this)',
),
'#parents' => array(
'alternatives',
$i,
'score_if_chosen',
),
);
$default_value = $short['score_if_not_chosen'];
if (!isset($default_value)) {
$default_value = '0';
}
$form['alternatives'][$i]['advanced']['score_if_not_chosen'] = array(
'#type' => 'textfield',
'#title' => t('Score if not chosen'),
'#size' => 4,
'#maxlength' => 4,
'#default_value' => $default_value,
'#description' => t('This score is added to the users total score if the user doesn\'t choose this alternative. Only used if multiple answers are allowed.'),
'#attributes' => array(
'onkeypress' => 'refreshCorrect(this)',
'onkeyup' => 'refreshCorrect(this)',
'onchange' => 'refreshCorrect(this)',
),
'#parents' => array(
'alternatives',
$i,
'score_if_not_chosen',
),
);
}
// ahah helper tag. New questions will be inserted before this tag
$form['alternatives']["placeholder"] = array(
'#type' => 'markup',
'#value' => '<DIV id=\'placeholder\'></DIV>',
);
// We can't send the get values to the ahah callback the normal way, so we do it like this.
$form['get'] = array(
'#type' => 'value',
'#value' => $get,
);
$form['alternatives']['multichoice_add_alternative'] = array(
'#type' => 'submit',
'#value' => t('Add more alternatives'),
'#submit' => array(
'multichoice_more_choices_submit',
),
// If no javascript action.
'#ahah' => array(
'path' => 'node/add/multichoice/add_alternative_ahah',
'wrapper' => 'placeholder',
'effect' => 'slide',
'method' => 'before',
),
);
return $form;
}
/**
* Helper function provding the default settings for the creation form.
*
* @return
* Array with the default settings
*/
private function getDefaultAltSettings() {
// If the node is beeing updated the default settings are those stored in the node
if (isset($this->node->nid)) {
$settings['choice_multi'] = $this->node->choice_multi;
$settings['choice_random'] = $this->node->choice_random;
$settings['choice_boolean'] = $this->node->choice_boolean;
}
elseif ($settings = $this
->getUserSettings()) {
}
else {
$settings['choice_multi'] = 0;
$settings['choice_random'] = 0;
$settings['choice_boolean'] = 0;
}
return $settings;
}
/**
* Fetches the users default settings for the creation form
*
* @return
* The users default node settings
*/
private function getUserSettings() {
global $user;
$sql = 'SELECT choice_multi, choice_boolean, choice_random
FROM {quiz_multichoice_user_settings}
WHERE uid = %d';
$res = db_query($sql, $user->uid);
if ($arr = db_fetch_array($res)) {
return $arr;
}
else {
return FALSE;
}
}
/**
* Fetches the users default settings from the creation form
*/
private function saveUserSettings() {
global $user;
$sql = 'REPLACE INTO {quiz_multichoice_user_settings}
(uid, choice_random, choice_multi, choice_boolean)
VALUES (%d, %d, %d, %d)';
db_query($sql, $user->uid, $this->node->choice_random, $this->node->choice_multi, $this->node->choice_boolean);
}
/**
* Implementation of getMaximumScore.
*
* @see QuizQuestion#getMaximumScore()
*/
public function getMaximumScore() {
if ($this->node->choice_boolean) {
return 1;
}
$max = 0;
for ($i = 0; isset($this->node->alternatives[$i]); $i++) {
$short = $this->node->alternatives[$i];
if ($this->node->choice_multi) {
$max += max($short['score_if_chosen'], $short['score_if_not_chosen']);
}
else {
$max = max($max, $short['score_if_chosen'], $short['score_if_not_chosen']);
}
}
return max($max, 1);
}
}
/**
* Extension of QuizQuestionResponse
*/
class MultichoiceResponse extends QuizQuestionResponse {
/**
* ID of the answers.
*/
protected $user_answer_ids;
protected $choice_order;
/**
* Constructor
*/
public function __construct($result_id, stdClass $question_node, $tries = NULL) {
parent::__construct($result_id, $question_node, $tries);
$this->user_answer_ids = array();
// tries is the tries part of the post data
if (is_array($tries)) {
if (isset($tries['choice_order'])) {
$this->choice_order = $tries['choice_order'];
}
unset($tries['choice_order']);
if (is_array($tries['answer'])) {
foreach ($tries['answer'] as $answer_id) {
$this->user_answer_ids[] = $answer_id;
$this->answer = $this->user_answer_ids;
//@todo: Stop using user_answer_ids and only use answer instead...
}
}
elseif (isset($tries['answer'])) {
$this->user_answer_ids[] = $tries['answer'];
}
}
else {
$sql = 'SELECT answer_id
FROM {quiz_multichoice_user_answers} ua
LEFT OUTER JOIN {quiz_multichoice_user_answer_multi} uam ON(uam.user_answer_id = ua.id)
WHERE ua.result_id = %d AND ua.question_nid = %d AND ua.question_vid = %d';
$res = db_query($sql, $result_id, $this->question->nid, $this->question->vid);
while ($res_o = db_fetch_object($res)) {
$this->user_answer_ids[] = $res_o->answer_id;
}
}
}
/**
* Implementation of isValid
*
* @see QuizQuestionResponse#isValid()
*/
public function isValid() {
if ($this->question->choice_multi) {
return TRUE;
}
if (empty($this->user_answer_ids)) {
return t('You must provide an answer');
}
// Perform extra check since FAPI isn't beeing used:
if (count($this->user_answer_ids) > 1) {
return t('You are only allowed to select one answer');
}
return TRUE;
}
/**
* Implementation of save
*
* @see QuizQuestionResponse#save()
*/
public function save() {
$sql = "INSERT INTO {quiz_multichoice_user_answers}\n (result_id, question_vid, question_nid, choice_order)\n VALUES (%d, %d, %d, '%s')";
db_query($sql, $this->rid, $this->question->vid, $this->question->nid, $this->choice_order);
$user_answer_id = db_last_insert_id('{quiz_multichoice_user_answers}', 'id');
for ($i = 0; $i < count($this->user_answer_ids); $i++) {
$sql = 'INSERT INTO {quiz_multichoice_user_answer_multi}
(user_answer_id, answer_id)
VALUES(%d, %d)';
db_query($sql, $user_answer_id, $this->user_answer_ids[$i]);
}
}
/**
* Implementation of delete
*
* @see QuizQuestionResponse#delete()
*/
public function delete() {
$sql = 'DELETE FROM {quiz_multichoice_user_answer_multi}
USING {quiz_multichoice_user_answer_multi}
INNER JOIN {quiz_multichoice_user_answers}
ON {quiz_multichoice_user_answer_multi}.user_answer_id = {quiz_multichoice_user_answers}.id
WHERE {quiz_multichoice_user_answers}.question_nid = %d
AND {quiz_multichoice_user_answers}.question_vid = %d
AND {quiz_multichoice_user_answers}.result_id = %d';
db_query($sql, $this->question->nid, $this->question->vid, $this->rid);
$sql = 'DELETE FROM {quiz_multichoice_user_answers}
WHERE result_id = %d AND question_nid = %d AND question_vid = %d';
db_query($sql, $this->rid, $this->question->nid, $this->question->vid);
}
/**
* Implementation of score
*
* @return uint
*
* @see QuizQuestionResponse#score()
*/
public function score() {
if ($this->question->choice_boolean || $this
->isAllWrong()) {
$score = 1;
foreach ($this->question->alternatives as $key => $alt) {
if (in_array($alt['id'], $this->user_answer_ids)) {
if ($alt['score_if_chosen'] <= $alt['score_if_not_chosen']) {
$score = 0;
}
}
else {
if ($alt['score_if_chosen'] > $alt['score_if_not_chosen']) {
$score = 0;
}
}
}
}
else {
$score = 0;
foreach ($this->question->alternatives as $key => $alt) {
if (in_array($alt['id'], $this->user_answer_ids)) {
$score += $alt['score_if_chosen'];
}
else {
$score += $alt['score_if_not_chosen'];
}
}
}
return $score;
}
/**
* If all answers in a question is wrong
*
* @return boolean
* TRUE if all answers are wrong. False otherwise.
*/
public function isAllWrong() {
foreach ($this->question->alternatives as $key => $alt) {
if ($alt['score_if_chosen'] > 0 || $alt['score_if_not_chosen'] > 0) {
return FALSE;
}
}
return TRUE;
}
/**
* Implementation of getResponse
*
* @return answer
*
* @see QuizQuestionResponse#getResponse()
*/
public function getResponse() {
return $this->user_answer_ids;
}
/**
* Implementation of getReportFormResponse
*
* @see getReportFormResponse($showpoints, $showfeedback, $allow_scoring)
*/
public function getReportFormResponse($showpoints = TRUE, $showfeedback = TRUE, $allow_scoring = FALSE) {
$i = 0;
$this
->orderAlternatives($this->question->alternatives);
// Find the alternative with the highest score
if ($this->question->choice_multi == 0) {
$max_score_if_chosen = -999;
// TODO: Is is_array needed here?
while (isset($this->question->alternatives[$i]) && is_array($this->question->alternatives[$i])) {
$short = $this->question->alternatives[$i];
if ($short['score_if_chosen'] > $max_score_if_chosen) {
$max_score_if_chosen = $short['score_if_chosen'];
}
$i++;
}
$i = 0;
}
// Fetch all data for the report
$data = array();
while (isset($this->question->alternatives[$i])) {
$short = $this->question->alternatives[$i];
if (drupal_strlen($this
->checkMarkup($short['answer'], $short['answer_format'])) > 0) {
$alternative = array();
// Did the user choose the alternative?
$alternative['is_chosen'] = in_array($short['id'], $this->user_answer_ids);
// Questions where multiple answers isn't allowed are scored differently...
if ($this->question->choice_multi == 0) {
if ($this->question->choice_boolean == 0) {
if ($short['score_if_chosen'] > $short['score_if_not_chosen']) {
$alternative['is_correct'] = $short['score_if_chosen'] < $max_score_if_chosen ? 1 : 2;
}
else {
$alternative['is_correct'] = 0;
}
}
else {
$alternative['is_correct'] = $short['score_if_chosen'] > $short['score_if_not_chosen'] ? 2 : 0;
}
}
else {
$alternative['is_correct'] = $short['score_if_chosen'] > $short['score_if_not_chosen'] ? 2 : 0;
}
$alternative['answer'] = $this
->checkMarkup($short['answer'], $short['answer_format'], FALSE);
$not = $alternative['is_chosen'] ? '' : '_not';
$alternative['feedback'] = $this
->checkMarkup($short['feedback_if' . $not . '_chosen'], $short['feedback_if' . $not . '_chosen_format'], FALSE);
$data[] = $alternative;
}
$i++;
}
// Return themed report
return array(
'#type' => 'markup',
'#value' => theme('multichoice_response', $data),
);
}
/**
* Order the alternatives according to the choice order stored in the database
*
* @param array $alternatives
* The alternatives to be ordered
*/
private function orderAlternatives(array &$alternatives) {
if (!$this->question->choice_random) {
return;
}
$sql = "SELECT choice_order\n FROM {quiz_multichoice_user_answers}\n WHERE result_id = %d AND question_nid = %d AND question_vid = %d";
$result = db_result(db_query($sql, $this->rid, $this->question->nid, $this->question->vid));
if (!$result) {
return;
}
$order = explode(',', $result);
$newAlternatives = array();
foreach ($order as $value) {
foreach ($alternatives as $alternative) {
if ($alternative['id'] == $value) {
$newAlternatives[] = $alternative;
break;
}
}
}
$alternatives = $newAlternatives;
}
/**
* Run check_markup() on the field of the specified choice alternative
*
* @param $alternative
* String to be checked
* @param $format
* The input format to be used
* @param $check_user_access
* Whether or not we are to check the users access to the chosen format
* @return HTML markup
*/
private function checkMarkup($alternative, $format, $check_user_access = FALSE) {
// If the string is empty we don't run it through input filters(They might add empty tags).
if (drupal_strlen($alternative) == 0) {
return '';
}
return check_markup($alternative, $format, $check_user_access);
}
}
Classes
Name![]() |
Description |
---|---|
MultichoiceQuestion | Extension of QuizQuestion. |
MultichoiceResponse | Extension of QuizQuestionResponse |