View source
<?php
namespace Drupal\quiz_multichoice\Plugin\quiz\QuizQuestion;
use Drupal;
use Drupal\Core\Form\FormStateInterface;
use Drupal\paragraphs\Entity\Paragraph;
use Drupal\quiz\Entity\QuizQuestion;
use Drupal\quiz\Entity\QuizResultAnswer;
use function check_markup;
use function db_delete;
use function db_insert;
use function db_merge;
use function db_query;
use function db_update;
use function variable_get;
class MultichoiceQuestion extends QuizQuestion {
function save() {
return parent::save();
}
private function forgive() {
if ($this->node->choice_multi == 1) {
for ($i = 0; isset($this->node->alternatives[$i]); $i++) {
$short =& $this->node->alternatives[$i];
if ($short['score_if_chosen'] == $short['score_if_not_chosen'] || !is_numeric($short['score_if_chosen']) || !is_numeric($short['score_if_not_chosen'])) {
if (!empty($short['correct'])) {
$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 ($i = 0; isset($this->node->alternatives[$i]); $i++) {
$short =& $this->node->alternatives[$i];
$short['score_if_not_chosen'] = 0;
if (isset($short['correct']) && $short['correct'] == 1 && !_quiz_is_int($short['score_if_chosen'], 1)) {
$short['score_if_chosen'] = 1;
}
}
}
}
private function warn() {
$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'), 'quiz/' . $this->node->nid . '/edit', $link_options);
if ($num_corrects == 1) {
Drupal::messenger()
->addWarning(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::messenger()
->addWarning(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');
}
}
}
private function checkMarkup($alternativeIndex, $field, $check_user_access = FALSE) {
$alternative = $this->node->alternatives[$alternativeIndex];
return check_markup($alternative[$field]['value'], $alternative[$field]['format']);
}
public function saveNodeProperties($is_new = FALSE) {
$is_new = $is_new || !empty($this->node->revision);
$this
->warn();
if ($is_new) {
$id = db_insert('quiz_multichoice_properties')
->fields(array(
'nid' => $this->node->nid,
'vid' => $this->node->vid,
'choice_multi' => $this->node->choice_multi,
'choice_random' => $this->node->choice_random,
'choice_boolean' => $this->node->choice_boolean,
))
->execute();
for ($i = 0; isset($this->node->alternatives[$i]); $i++) {
if (drupal_strlen($this->node->alternatives[$i]['answer']['value']) > 0) {
$this
->insertAlternative($i);
}
}
}
else {
db_update('quiz_multichoice_properties')
->fields(array(
'choice_multi' => $this->node->choice_multi,
'choice_random' => $this->node->choice_random,
'choice_boolean' => $this->node->choice_boolean,
))
->condition('nid', $this->node->nid)
->condition('vid', $this->node->vid)
->execute();
$res = db_query('SELECT id FROM {quiz_multichoice_answers}
WHERE question_nid = :nid AND question_vid = :vid', array(
':nid' => $this->node->nid,
':vid' => $this->node->vid,
));
$ids_to_delete = array();
while ($res_o = $res
->fetch()) {
$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']['value']) > 0) {
if (!is_numeric($short['id'])) {
$this
->insertAlternative($i);
}
else {
$this
->updateAlternative($i);
$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_delete('quiz_multichoice_answers')
->condition('id', $id_to_delete)
->execute();
}
}
}
$this
->saveUserSettings();
}
private function _normalizeAlternative($alternatives) {
$copy = $alternatives;
if (is_array($alternatives['answer'])) {
$copy['answer'] = array_key_exists('value', $alternatives['answer']) ? $alternatives['answer']['value'] : NULL;
$copy['answer_format'] = array_key_exists('format', $alternatives['answer']) ? $alternatives['answer']['format'] : NULL;
}
if (is_array($alternatives['feedback_if_chosen'])) {
$copy['feedback_if_chosen'] = array_key_exists('value', $alternatives['feedback_if_chosen']) ? $alternatives['feedback_if_chosen']['value'] : NULL;
$copy['feedback_if_chosen_format'] = array_key_exists('format', $alternatives['feedback_if_chosen']) ? $alternatives['feedback_if_chosen']['format'] : NULL;
}
if (is_array($alternatives['feedback_if_not_chosen'])) {
$copy['feedback_if_not_chosen'] = array_key_exists('value', $alternatives['feedback_if_not_chosen']) ? $alternatives['feedback_if_not_chosen']['value'] : NULL;
$copy['feedback_if_not_chosen_format'] = array_key_exists('format', $alternatives['feedback_if_not_chosen']) ? $alternatives['feedback_if_not_chosen']['format'] : NULL;
}
return $copy;
}
private function insertAlternative($i) {
$alternatives = $this
->_normalizeAlternative($this->node->alternatives[$i]);
db_insert('quiz_multichoice_answers')
->fields(array(
'answer' => $alternatives['answer'],
'answer_format' => $alternatives['answer_format'],
'feedback_if_chosen' => $alternatives['feedback_if_chosen'],
'feedback_if_chosen_format' => $alternatives['feedback_if_chosen_format'],
'feedback_if_not_chosen' => $alternatives['feedback_if_not_chosen'],
'feedback_if_not_chosen_format' => $alternatives['feedback_if_not_chosen_format'],
'score_if_chosen' => $alternatives['score_if_chosen'],
'score_if_not_chosen' => $alternatives['score_if_not_chosen'],
'question_nid' => $this->node->nid,
'question_vid' => $this->node->vid,
'weight' => isset($alternatives['weight']) ? $alternatives['weight'] : $i,
))
->execute();
}
private function updateAlternative($i) {
$alternatives = $this
->_normalizeAlternative($this->node->alternatives[$i]);
db_update('quiz_multichoice_answers')
->fields(array(
'answer' => $alternatives['answer'],
'answer_format' => $alternatives['answer_format'],
'feedback_if_chosen' => $alternatives['feedback_if_chosen'],
'feedback_if_chosen_format' => $alternatives['feedback_if_chosen_format'],
'feedback_if_not_chosen' => $alternatives['feedback_if_not_chosen'],
'feedback_if_not_chosen_format' => $alternatives['feedback_if_not_chosen_format'],
'score_if_chosen' => $alternatives['score_if_chosen'],
'score_if_not_chosen' => $alternatives['score_if_not_chosen'],
'weight' => isset($alternatives['weight']) ? $alternatives['weight'] : $i,
))
->condition('id', $alternatives['id'])
->condition('question_nid', $this->node->nid)
->condition('question_vid', $this->node->vid)
->execute();
}
public function validateNode(array &$form) {
if ($this->node->choice_multi == 0) {
$found_one_correct = FALSE;
for ($i = 0; isset($this->node->alternatives[$i]) && 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) {
}
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.'));
}
}
}
}
public function delete($only_this_version = FALSE) {
$delete_properties = db_delete('quiz_multichoice_properties')
->condition('nid', $this->node->nid);
$delete_answers = db_delete('quiz_multichoice_answers')
->condition('question_nid', $this->node->nid);
if ($only_this_version) {
$delete_properties
->condition('vid', $this->node->vid);
$delete_answers
->condition('question_vid', $this->node->vid);
}
$delete_properties
->execute();
$delete_answers
->execute();
parent::delete($only_this_version);
}
public function getNodeProperties() {
if (isset($this->nodeProperties) && !empty($this->nodeProperties)) {
return $this->nodeProperties;
}
$props = parent::getNodeProperties();
$res_a = db_query('SELECT choice_multi, choice_random, choice_boolean FROM {quiz_multichoice_properties}
WHERE nid = :nid AND vid = :vid', array(
':nid' => $this->node->nid,
':vid' => $this->node->vid,
))
->fetchAssoc();
if (is_array($res_a)) {
$props = array_merge($props, $res_a);
}
$res = db_query('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, weight
FROM {quiz_multichoice_answers}
WHERE question_nid = :question_nid AND question_vid = :question_vid
ORDER BY weight', array(
':question_nid' => $this->node->nid,
':question_vid' => $this->node->vid,
));
$props['alternatives'] = array();
while ($res_arr = $res
->fetchAssoc()) {
$props['alternatives'][] = array(
'id' => $res_arr['id'],
'answer' => array(
'value' => $res_arr['answer'],
'format' => $res_arr['answer_format'],
),
'feedback_if_chosen' => array(
'value' => $res_arr['feedback_if_chosen'],
'format' => $res_arr['feedback_if_chosen_format'],
),
'feedback_if_not_chosen' => array(
'value' => $res_arr['feedback_if_not_chosen'],
'format' => $res_arr['feedback_if_not_chosen_format'],
),
'score_if_chosen' => $res_arr['score_if_chosen'],
'score_if_not_chosen' => $res_arr['score_if_not_chosen'],
'weight' => $res_arr['weight'],
);
}
$this->nodeProperties = $props;
return $props;
}
public function getNodeView() {
$content = parent::getNodeView();
if ($this->node->choice_random) {
$this
->shuffle($this->node->alternatives);
}
$content['answers'] = array(
'#markup' => theme('multichoice_answer_node_view', array(
'alternatives' => $this->node->alternatives,
'show_correct' => $this
->viewCanRevealCorrect(),
)),
'#weight' => 2,
);
return $content;
}
public function getAnsweringForm(FormStateInterface $form_state, QuizResultAnswer $quizQuestionResultAnswer) {
$element = parent::getAnsweringForm($form_state, $quizQuestionResultAnswer);
foreach ($this
->get('alternatives')
->referencedEntities() as $alternative) {
$uuid = $alternative
->get('uuid')
->getString();
$alternatives[$uuid] = $alternative;
}
$element['user_answer'] = [
'#type' => 'tableselect',
'#header' => [
'answer' => t('Answer'),
],
'#js_select' => FALSE,
'#multiple' => $this
->get('choice_multi')
->getString(),
];
foreach ($alternatives as $uuid => $alternative) {
$vid = $alternative
->getRevisionId();
$answer_markup = check_markup($alternative
->get('multichoice_answer')
->getValue()[0]['value'], $alternative
->get('multichoice_answer')
->getValue()[0]['format']);
$element['user_answer']['#options'][$vid]['title']['data']['#title'] = $answer_markup;
$element['user_answer']['#options'][$vid]['answer'] = $answer_markup;
}
if ($this
->get('choice_random')
->getString()) {
$element['choice_order'] = array(
'#type' => 'hidden',
'#value' => implode(',', $this
->shuffle($element['user_answer']['#options'])),
);
}
if ($quizQuestionResultAnswer
->isAnswered()) {
$choices = $quizQuestionResultAnswer
->getResponse();
if ($this
->get('choice_multi')
->getString()) {
foreach ($choices as $choice) {
$element['user_answer']['#default_value'][$choice] = TRUE;
}
}
else {
$element['user_answer']['#default_value'] = reset($choices);
}
}
return $element;
}
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;
}
public function getCreationForm(array &$form_state = NULL) {
$form = array();
$type = node_type_get_type($this->node);
$options = array();
$get = $_GET;
unset($get['q']);
if (!empty($get)) {
$options['query'] = $get;
}
$action = url('quiz/add/' . $type->type, $options);
if (isset($this->node->nid)) {
$action = url('quiz/' . $this->node->nid . '/edit', $options);
}
$form['#action'] = $action;
drupal_add_tabledrag('multichoice-alternatives-table', 'order', 'sibling', 'multichoice-alternative-weight');
$form['alternatives'] = array(
'#type' => 'fieldset',
'#title' => t('Answer'),
'#collapsible' => TRUE,
'#collapsed' => FALSE,
'#weight' => -4,
'#tree' => TRUE,
);
$default_settings = $this
->getDefaultAltSettings();
$form['alternatives']['settings'] = array(
'#type' => 'fieldset',
'#title' => t('Settings'),
'#collapsible' => TRUE,
'#collapsed' => FALSE,
'#description' => t('Your settings will be remembered.'),
'#weight' => 30,
);
$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 being taken.', array(
'@quiz' => _quiz_get_quiz_name(),
)),
'#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',
),
);
$form['alternatives']['#theme'][] = 'multichoice_creation_form';
$i = 0;
if (isset($form_state['values']['op']) && $form_state['values']['op'] == t('Add choice')) {
$form_state['choice_count']++;
}
else {
$form_state['choice_count'] = max(variable_get('multichoice_def_num_of_alts', 2), isset($this->node->alternatives) ? count($this->node->alternatives) : 0);
}
$form['alternatives']['#prefix'] = '<div class="clear-block" id="multichoice-alternatives-wrapper">';
$form['alternatives']['#suffix'] = '</div>';
$form['alternatives']['#theme'] = array(
'multichoice_alternative_creation_table',
);
for ($i = 0; $i < $form_state['choice_count']; $i++) {
$short = isset($this->node->alternatives[$i]) ? $this->node->alternatives[$i] : NULL;
$form['alternatives'][$i] = array(
'#type' => 'container',
'#collapsible' => TRUE,
'#collapsed' => FALSE,
);
if (is_array($short)) {
if ($short['score_if_chosen'] == $short['score_if_not_chosen']) {
$correct_default = isset($short['correct']) ? $short['correct'] : FALSE;
}
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' => 'Multichoice.refreshScores(this, ' . variable_get('multichoice_def_scoring', 0) . ')',
),
);
$form['alternatives'][$i]['id'] = array(
'#type' => 'value',
'#value' => $short['id'],
);
$form['alternatives'][$i]['answer'] = array(
'#type' => 'text_format',
'#default_value' => $short['answer']['value'],
'#required' => $i < 2,
'#format' => isset($short['answer']['format']) ? $short['answer']['format'] : NULL,
'#rows' => 3,
);
$form['alternatives'][$i]['advanced'] = array(
'#type' => 'fieldset',
'#title' => t('Advanced options'),
'#collapsible' => TRUE,
'#collapsed' => TRUE,
);
$form['alternatives'][$i]['advanced']['feedback_if_chosen'] = array(
'#type' => 'text_format',
'#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']['value'],
'#format' => isset($short['feedback_if_chosen']['format']) ? $short['feedback_if_chosen']['format'] : NULL,
'#rows' => 3,
);
$form['alternatives'][$i]['advanced']['helper']['feedback_if_not_chosen'] = array(
'#type' => 'text_format',
'#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']['value'],
'#format' => isset($short['feedback_if_not_chosen']['format']) ? $short['feedback_if_not_chosen']['format'] : NULL,
'#rows' => 3,
);
$default_value = isset($this->node->alternatives[$i]['score_if_chosen']) ? $this->node->alternatives[$i]['score_if_chosen'] : 0;
$form['alternatives'][$i]['advanced']['score_if_chosen'] = array(
'#type' => 'textfield',
'#title' => t('Score if chosen'),
'#size' => 4,
'#default_value' => $default_value,
'#description' => t("This score is added to the user's total score if the user chooses this alternative."),
'#attributes' => array(
'onkeypress' => 'Multichoice.refreshCorrect(this)',
'onkeyup' => 'Multichoice.refreshCorrect(this)',
'onchange' => 'Multichoice.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,
'#default_value' => $default_value,
'#description' => t("This score is added to the user's total score if the user doesn't choose this alternative. Only used if multiple answers are allowed."),
'#attributes' => array(
'onkeypress' => 'Multichoice.refreshCorrect(this)',
'onkeyup' => 'Multichoice.refreshCorrect(this)',
'onchange' => 'Multichoice.refreshCorrect(this)',
),
'#parents' => array(
'alternatives',
$i,
'score_if_not_chosen',
),
);
$form['alternatives'][$i]['weight'] = array(
'#type' => 'textfield',
'#size' => 2,
'#attributes' => array(
'class' => array(
'multichoice-alternative-weight',
),
),
'#default_value' => isset($this->node->alternatives[$i]['weight']) ? $this->node->alternatives[$i]['weight'] : $i,
);
$form['alternatives'][$i]['remove_button'] = array(
'#delta' => $i,
'#name' => 'alternatives__' . $i . '__remove_button',
'#type' => 'submit',
'#value' => t('Remove'),
'#validate' => array(),
'#submit' => array(
'multichoice_remove_alternative_submit',
),
'#limit_validation_errors' => array(),
'#ajax' => array(
'callback' => 'multichoice_remove_alternative_ajax_callback',
'effect' => 'fade',
'wrapper' => 'multichoice-alternatives-wrapper',
),
'#weight' => 1000,
);
}
$form['alternatives']['multichoice_add_alternative'] = array(
'#type' => 'button',
'#value' => t('Add choice'),
'#ajax' => array(
'method' => 'replace',
'wrapper' => 'multichoice-alternatives-wrapper',
'callback' => 'multichoice_add_alternative_ajax_callback',
),
'#weight' => 20,
'#limit_validation_errors' => array(),
);
return $form;
}
private function getDefaultAltSettings() {
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;
}
private function getUserSettings() {
$user = \Drupal::currentUser();
$res = db_query('SELECT choice_multi, choice_boolean, choice_random
FROM {quiz_multichoice_user_settings}
WHERE uid = :uid', array(
':uid' => $user
->id(),
))
->fetchAssoc();
if ($res) {
return $res;
}
else {
return FALSE;
}
}
private function saveUserSettings() {
$user = \Drupal::currentUser();
db_merge('quiz_multichoice_user_settings')
->key(array(
'uid' => $user
->id(),
))
->fields(array(
'choice_random' => $this->node->choice_random,
'choice_multi' => $this->node->choice_multi,
'choice_boolean' => $this->node->choice_boolean,
))
->execute();
}
public function getMaximumScore() {
if ($this
->get('choice_boolean')
->getString()) {
return 1;
}
$maxes = [
0,
];
foreach ($this
->get('alternatives')
->referencedEntities() as $alternative) {
$maxes[] = max($alternative
->get('multichoice_score_chosen')
->getString(), $alternative
->get('multichoice_score_not_chosen')
->getString());
}
if ($this
->get('choice_multi')
->getString()) {
return array_sum($maxes);
}
else {
return max($maxes);
}
}
public static function getAnsweringFormValidate(array &$element, FormStateInterface $form_state) {
$mcq = $form_state
->getBuildInfo()['args'][0];
if (!$mcq
->get('choice_multi')
->getString() && empty($element['user_answer']['#value'])) {
$form_state
->setError($element, t('You must provide an answer.'));
}
parent::getAnsweringFormValidate($element, $form_state);
}
}