.
/**
* This contains functions that are called from within the quiz module only
* Functions that are also called by core Moodle are in {@link lib.php}
* This script also loads the code in {@link questionlib.php} which holds
* the module-indpendent code for handling questions and which in turn
* initialises all the questiontype classes.
*
* @package mod_quiz
* @copyright 1999 onwards Martin Dougiamas and others {@link http://moodle.com}
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
defined('MOODLE_INTERNAL') || die();
require_once($CFG->dirroot . '/mod/quiz/locallib.php');
define('NUM_QS_TO_SHOW_IN_RANDOM', 3);
/**
* Verify that the question exists, and the user has permission to use it.
* Does not return. Throws an exception if the question cannot be used.
* @param int $questionid The id of the question.
*/
function quiz_require_question_use($questionid) {
global $DB;
$question = $DB->get_record('question', array('id' => $questionid), '*', MUST_EXIST);
question_require_capability_on($question, 'use');
}
/**
* Verify that the question exists, and the user has permission to use it.
* @param object $quiz the quiz settings.
* @param int $slot which question in the quiz to test.
* @return bool whether the user can use this question.
*/
function quiz_has_question_use($quiz, $slot) {
global $DB;
$question = $DB->get_record_sql("
SELECT q.*
FROM {quiz_slots} slot
JOIN {question} q ON q.id = slot.questionid
WHERE slot.quizid = ? AND slot.slot = ?", array($quiz->id, $slot));
if (!$question) {
return false;
}
return question_has_capability_on($question, 'use');
}
/**
* Remove a question from a quiz
* @param object $quiz the quiz object.
* @param int $questionid The id of the question to be deleted.
*/
function quiz_remove_slot($quiz, $slotnumber) {
global $DB;
$slot = $DB->get_record('quiz_slots', array('quizid' => $quiz->id, 'slot' => $slotnumber));
$maxslot = $DB->get_field_sql('SELECT MAX(slot) FROM {quiz_slots} WHERE quizid = ?', array($quiz->id));
if (!$slot) {
return;
}
$trans = $DB->start_delegated_transaction();
$DB->delete_records('quiz_slots', array('id' => $slot->id));
for ($i = $slot->slot + 1; $i <= $maxslot; $i++) {
$DB->set_field('quiz_slots', 'slot', $i - 1,
array('quizid' => $quiz->id, 'slot' => $i));
}
$qtype = $DB->get_field('question', 'qtype', array('id' => $slot->questionid));
if ($qtype === 'random') {
// This function automatically checks if the question is in use, and won't delete if it is.
question_delete_question($slot->questionid);
}
$trans->allow_commit();
}
/**
* Remove an empty page from the quiz layout. If that is not possible, do nothing.
* @param object $quiz the quiz settings.
* @param int $pagenumber the page number to delete.
*/
function quiz_delete_empty_page($quiz, $pagenumber) {
global $DB;
if ($DB->record_exists('quiz_slots', array('quizid' => $quiz->id, 'page' => $pagenumber))) {
// This was not an empty page.
return;
}
$DB->execute('UPDATE {quiz_slots} SET page = page - 1 WHERE quizid = ? AND page > ?',
array($quiz->id, $pagenumber));
}
/**
* Add a question to a quiz
*
* Adds a question to a quiz by updating $quiz as well as the
* quiz and quiz_slots tables. It also adds a page break if required.
* @param int $questionid The id of the question to be added
* @param object $quiz The extended quiz object as used by edit.php
* This is updated by this function
* @param int $page Which page in quiz to add the question on. If 0 (default),
* add at the end
* @param float $maxmark The maximum mark to set for this question. (Optional,
* defaults to question.defaultmark.
* @return bool false if the question was already in the quiz
*/
function quiz_add_quiz_question($questionid, $quiz, $page = 0, $maxmark = null) {
global $DB;
$slots = $DB->get_records('quiz_slots', array('quizid' => $quiz->id),
'slot', 'questionid, slot, page, id');
if (array_key_exists($questionid, $slots)) {
return false;
}
$trans = $DB->start_delegated_transaction();
$maxpage = 1;
$numonlastpage = 0;
foreach ($slots as $slot) {
if ($slot->page > $maxpage) {
$maxpage = $slot->page;
$numonlastpage = 1;
} else {
$numonlastpage += 1;
}
}
// Add the new question instance.
$slot = new stdClass();
$slot->quizid = $quiz->id;
$slot->questionid = $questionid;
if ($maxmark !== null) {
$slot->maxmark = $maxmark;
} else {
$slot->maxmark = $DB->get_field('question', 'defaultmark', array('id' => $questionid));
}
if (is_int($page) && $page >= 1) {
// Adding on a given page.
$lastslotbefore = 0;
foreach (array_reverse($slots) as $otherslot) {
if ($otherslot->page > $page) {
$DB->set_field('quiz_slots', 'slot', $otherslot->slot + 1, array('id' => $otherslot->id));
} else {
$lastslotbefore = $otherslot->slot;
break;
}
}
$slot->slot = $lastslotbefore + 1;
$slot->page = min($page, $maxpage + 1);
} else {
$lastslot = end($slots);
if ($lastslot) {
$slot->slot = $lastslot->slot + 1;
} else {
$slot->slot = 1;
}
if ($quiz->questionsperpage && $numonlastpage >= $quiz->questionsperpage) {
$slot->page = $maxpage + 1;
} else {
$slot->page = $maxpage;
}
}
$DB->insert_record('quiz_slots', $slot);
$trans->allow_commit();
}
/**
* Add a random question to the quiz at a given point.
* @param object $quiz the quiz settings.
* @param int $addonpage the page on which to add the question.
* @param int $categoryid the question category to add the question from.
* @param int $number the number of random questions to add.
* @param bool $includesubcategories whether to include questoins from subcategories.
*/
function quiz_add_random_questions($quiz, $addonpage, $categoryid, $number,
$includesubcategories) {
global $DB;
$category = $DB->get_record('question_categories', array('id' => $categoryid));
if (!$category) {
print_error('invalidcategoryid', 'error');
}
$catcontext = context::instance_by_id($category->contextid);
require_capability('moodle/question:useall', $catcontext);
// Find existing random questions in this category that are
// not used by any quiz.
if ($existingquestions = $DB->get_records_sql(
"SELECT q.id, q.qtype FROM {question} q
WHERE qtype = 'random'
AND category = ?
AND " . $DB->sql_compare_text('questiontext') . " = ?
AND NOT EXISTS (
SELECT *
FROM {quiz_slots}
WHERE questionid = q.id)
ORDER BY id", array($category->id, ($includesubcategories ? '1' : '0')))) {
// Take as many of these as needed.
while (($existingquestion = array_shift($existingquestions)) && $number > 0) {
quiz_add_quiz_question($existingquestion->id, $quiz, $addonpage);
$number -= 1;
}
}
if ($number <= 0) {
return;
}
// More random questions are needed, create them.
for ($i = 0; $i < $number; $i += 1) {
$form = new stdClass();
$form->questiontext = array('text' => ($includesubcategories ? '1' : '0'), 'format' => 0);
$form->category = $category->id . ',' . $category->contextid;
$form->defaultmark = 1;
$form->hidden = 1;
$form->stamp = make_unique_id_code(); // Set the unique code (not to be changed).
$question = new stdClass();
$question->qtype = 'random';
$question = question_bank::get_qtype('random')->save_question($question, $form);
if (!isset($question->id)) {
print_error('cannotinsertrandomquestion', 'quiz');
}
quiz_add_quiz_question($question->id, $quiz, $addonpage);
}
}
/**
* Add a page break after a particular slot.
* @param object $quiz the quiz settings.
* @param int $slot the slot to add the page break after.
*/
function quiz_add_page_break_after_slot($quiz, $slot) {
global $DB;
$DB->execute('UPDATE {quiz_slots} SET page = page + 1 WHERE quizid = ? AND slot > ?',
array($quiz->id, $slot));
}
/**
* Change the max mark for a slot.
*
* Saves changes to the question grades in the quiz_slots table and any
* corresponding question_attempts.
* It does not update 'sumgrades' in the quiz table.
*
* @param stdClass $slot row from the quiz_slots table.
* @param float $maxmark the new maxmark.
*/
function quiz_update_slot_maxmark($slot, $maxmark) {
global $DB;
if (abs($maxmark - $slot->maxmark) < 1e-7) {
// Grade has not changed. Nothing to do.
return;
}
$slot->maxmark = $maxmark;
$DB->update_record('quiz_slots', $slot);
question_engine::set_max_mark_in_attempts(new qubaids_for_quiz($slot->quizid),
$slot->slot, $maxmark);
}
/**
* Private function used by the following two.
* @param object $quiz the quiz settings.
* @param int $slotnumber the slot to move up.
* @param int $shift +1 means move down, -1 means move up.
*/
function _quiz_move_question($quiz, $slotnumber, $shift) {
global $DB;
if (!$slotnumber || !($shift == 1 || $shift == -1)) {
return;
}
$slot = $DB->get_record('quiz_slots',
array('quizid' => $quiz->id, 'slot' => $slotnumber));
if (!$slot) {
return;
}
$otherslot = $DB->get_record('quiz_slots',
array('quizid' => $quiz->id, 'slot' => $slotnumber + $shift));
if (!$otherslot) {
// Must be first or last question being moved further that way if we can.
if ($shift + $slot->page > 0) {
$DB->set_field('quiz_slots', 'page', $slot->page + $shift, array('id' => $slot->id));
}
return;
}
if ($otherslot->page != $slot->page) {
$DB->set_field('quiz_slots', 'page', $slot->page + $shift, array('id' => $slot->id));
return;
}
$trans = $DB->start_delegated_transaction();
$DB->set_field('quiz_slots', 'slot', -1, array('id' => $slot->id));
$DB->set_field('quiz_slots', 'slot', $slot->slot, array('id' => $otherslot->id));
$DB->set_field('quiz_slots', 'slot', $otherslot->slot, array('id' => $slot->id));
$trans->allow_commit();
}
/**
* Move a particular question one space earlier in the quiz.
* If that is not possible, do nothing.
* @param object $quiz the quiz settings.
* @param int $slot the slot to move up.
*/
function quiz_move_question_up($quiz, $slot) {
_quiz_move_question($quiz, $slot, -1);
}
/**
* Move a particular question one space later in the quiz.
* If that is not possible, do nothing.
* @param object $quiz the quiz settings.
* @param int $slot the slot to move down.
*/
function quiz_move_question_down($quiz, $slot) {
return _quiz_move_question($quiz, $slot, 1);
}
/**
* Prints a list of quiz questions for the edit.php main view for edit
* ($reordertool = false) and order and paging ($reordertool = true) tabs
*
* @param object $quiz The quiz settings.
* @param moodle_url $pageurl The url of the current page with the parameters required
* for links returning to the current page, as a moodle_url object
* @param bool $allowdelete Indicates whether the delete icons should be displayed
* @param bool $reordertool Indicates whether the reorder tool should be displayed
* @param bool $quiz_qbanktool Indicates whether the question bank should be displayed
* @param bool $hasattempts Indicates whether the quiz has attempts
* @param object $defaultcategoryobj
* @param bool $canaddquestion is the user able to add and use questions anywere?
* @param bool $canaddrandom is the user able to add random questions anywere?
*/
function quiz_print_question_list($quiz, $pageurl, $allowdelete, $reordertool,
$quiz_qbanktool, $hasattempts, $defaultcategoryobj, $canaddquestion, $canaddrandom) {
global $CFG, $DB, $OUTPUT;
$strorder = get_string('order');
$strquestionname = get_string('questionname', 'quiz');
$strmaxmark = get_string('markedoutof', 'question');
$strremove = get_string('remove', 'quiz');
$stredit = get_string('edit');
$strview = get_string('view');
$straction = get_string('action');
$strmove = get_string('move');
$strmoveup = get_string('moveup');
$strmovedown = get_string('movedown');
$strsave = get_string('save', 'quiz');
$strreorderquestions = get_string('reorderquestions', 'quiz');
$strselectall = get_string('selectall', 'quiz');
$strselectnone = get_string('selectnone', 'quiz');
$strtype = get_string('type', 'quiz');
$strpreview = get_string('preview', 'quiz');
$questions = $DB->get_records_sql("SELECT slot.slot, q.*, qc.contextid, slot.page, slot.maxmark
FROM {quiz_slots} slot
LEFT JOIN {question} q ON q.id = slot.questionid
LEFT JOIN {question_categories} qc ON qc.id = q.category
WHERE slot.quizid = ?
ORDER BY slot.slot", array($quiz->id));
$lastindex = count($questions) - 1;
$disabled = '';
$pagingdisabled = '';
if ($hasattempts) {
$disabled = 'disabled="disabled"';
}
if ($hasattempts || $quiz->shufflequestions) {
$pagingdisabled = 'disabled="disabled"';
}
$reordercontrolssetdefaultsubmit = '
";
if ($reordertool) {
echo '';
}
}
/**
* Print all the controls for adding questions directly into the
* specific page in the edit tab of edit.php
*
* @param object $quiz The quiz settings.
* @param moodle_url $pageurl The url of the current page with the parameters required
* for links returning to the current page, as a moodle_url object
* @param int $page the current page number.
* @param bool $hasattempts Indicates whether the quiz has attempts
* @param object $defaultcategoryobj
* @param bool $canaddquestion is the user able to add and use questions anywere?
* @param bool $canaddrandom is the user able to add random questions anywere?
*/
function quiz_print_pagecontrols($quiz, $pageurl, $page, $hasattempts,
$defaultcategoryobj, $canaddquestion, $canaddrandom) {
global $CFG, $OUTPUT;
static $randombuttoncount = 0;
$randombuttoncount++;
echo '
';
// Get the current context.
$thiscontext = context_course::instance($quiz->course);
$contexts = new question_edit_contexts($thiscontext);
// Get the default category.
list($defaultcategoryid) = explode(',', $pageurl->param('cat'));
if (empty($defaultcategoryid)) {
$defaultcategoryid = $defaultcategoryobj->id;
}
if ($canaddquestion) {
// Create the url the question page will return to.
$returnurladdtoquiz = new moodle_url($pageurl, array('addonpage' => $page));
// Print a button linking to the choose question type page.
$returnurladdtoquiz = $returnurladdtoquiz->out_as_local_url(false);
$newquestionparams = array('returnurl' => $returnurladdtoquiz,
'cmid' => $quiz->cmid, 'appendqnumstring' => 'addquestion');
create_new_question_button($defaultcategoryid, $newquestionparams,
get_string('addaquestion', 'quiz'),
get_string('createquestionandadd', 'quiz'), $hasattempts);
}
if ($hasattempts) {
$disabled = 'disabled="disabled"';
} else {
$disabled = '';
}
if ($canaddrandom) {
?>
";
}
/**
* Print a given single question in quiz for the edit tab of edit.php.
* Meant to be used from quiz_print_question_list()
*
* @param object $question A question object from the database questions table
* @param object $returnurl The url to get back to this page, for example after editing.
* @param object $quiz The quiz in the context of which the question is being displayed
*/
function quiz_print_singlequestion($question, $returnurl, $quiz) {
echo '
\n";
}
/**
* Print a given random question in quiz for the edit tab of edit.php.
* Meant to be used from quiz_print_question_list()
*
* @param object $question A question object from the database questions table
* @param object $questionurl The url of the question editing page as a moodle_url object
* @param object $quiz The quiz in the context of which the question is being displayed
* @param bool $quiz_qbanktool Indicate to this function if the question bank window open
*/
function quiz_print_randomquestion($question, $pageurl, $quiz, $quiz_qbanktool) {
global $DB, $OUTPUT;
echo '
';
if (!$category = $DB->get_record('question_categories',
array('id' => $question->category))) {
echo $OUTPUT->notification('Random question category not found!');
return;
}
echo '
';
if ($questioncount == 0) {
// No questions in category, give an error plus instructions.
echo '';
print_string('noquestionsnotinuse', 'quiz');
echo '';
echo ' ';
// Embed the link into the string with instructions.
$a = new stdClass();
$a->catname = '' . $category->name . '';
$a->link = $linkcategorycontents;
echo get_string('addnewquestionsqbank', 'quiz', $a);
} else {
// Category has questions.
// Get a sample from the database.
$questionidstoshow = array_slice($questionids, 0, NUM_QS_TO_SHOW_IN_RANDOM);
$questionstoshow = $DB->get_records_list('question', 'id', $questionidstoshow,
'', 'id, qtype, name, questiontext, questiontextformat');
// Then list them.
echo '
';
foreach ($questionstoshow as $subquestion) {
echo '
';
}
/**
* Print a given single question in quiz for the reordertool tab of edit.php.
* Meant to be used from quiz_print_question_list()
*
* @param object $question A question object from the database questions table
* @param object $questionurl The url of the question editing page as a moodle_url object
* @param object $quiz The quiz in the context of which the question is being displayed
*/
function quiz_print_singlequestion_reordertool($question, $returnurl, $quiz) {
echo '
\n";
}
/**
* Print a given random question in quiz for the reordertool tab of edit.php.
* Meant to be used from quiz_print_question_list()
*
* @param object $question A question object from the database questions table
* @param object $questionurl The url of the question editing page as a moodle_url object
* @param object $quiz The quiz in the context of which the question is being displayed
*/
function quiz_print_randomquestion_reordertool($question, $pageurl, $quiz) {
global $DB, $OUTPUT;
// Load the category, and the number of available questions in it.
if (!$category = $DB->get_record('question_categories', array('id' => $question->category))) {
echo $OUTPUT->notification('Random question category not found!');
return;
}
$questioncount = count(question_bank::get_qtype(
'random')->get_available_questions_from_category(
$category->id, $question->questiontext == '1', '0'));
$reordercheckboxlabel = '';
echo '
';
}
/**
* Print an icon to indicate the 'include subcategories' state of a random question.
* @param $question the random question.
*/
function print_random_option_icon($question) {
global $OUTPUT;
if (!empty($question->questiontext)) {
$icon = 'withsubcat';
$tooltip = get_string('randomwithsubcat', 'quiz');
} else {
$icon = 'nosubcat';
$tooltip = get_string('randomnosubcat', 'quiz');
}
echo '';
}
/**
* Creates a textual representation of a question for display.
*
* @param object $question A question object from the database questions table
* @param bool $showicon If true, show the question's icon with the question. False by default.
* @param bool $showquestiontext If true (default), show question text after question name.
* If false, show only question name.
* @param bool $return If true (default), return the output. If false, print it.
*/
function quiz_question_tostring($question, $showicon = false,
$showquestiontext = true, $return = true) {
global $COURSE;
$result = '';
$result .= '';
if ($showicon) {
$result .= print_question_icon($question, true);
echo ' ';
}
$result .= shorten_text(format_string($question->name), 200) . '';
if ($showquestiontext) {
$questiontext = question_utils::to_plain_text($question->questiontext,
$question->questiontextformat, array('noclean' => true, 'para' => false));
$questiontext = shorten_text($questiontext, 200);
$result .= '';
if (!empty($questiontext)) {
$result .= s($questiontext);
} else {
$result .= '';
$result .= get_string('questiontextisempty', 'quiz');
$result .= '';
}
$result .= '';
}
if ($return) {
return $result;
} else {
echo $result;
}
}
/**
* A column type for the add this question to the quiz.
*
* @copyright 2009 Tim Hunt
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class question_bank_add_to_quiz_action_column extends question_bank_action_column_base {
protected $stradd;
public function init() {
parent::init();
$this->stradd = get_string('addtoquiz', 'quiz');
}
public function get_name() {
return 'addtoquizaction';
}
protected function display_content($question, $rowclasses) {
if (!question_has_capability_on($question, 'use')) {
return;
}
// For RTL languages: switch right and left arrows.
if (right_to_left()) {
$movearrow = 't/removeright';
} else {
$movearrow = 't/moveleft';
}
$this->print_icon($movearrow, $this->stradd, $this->qbank->add_to_quiz_url($question->id));
}
public function get_required_fields() {
return array('q.id');
}
}
/**
* A column type for the name followed by the start of the question text.
*
* @copyright 2009 Tim Hunt
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class question_bank_question_name_text_column extends question_bank_question_name_column {
public function get_name() {
return 'questionnametext';
}
protected function display_content($question, $rowclasses) {
echo '
';
}
protected function display_options($recurse, $showhidden, $showquestiontext) {
debugging('display_options() is deprecated, see display_options_form() instead.', DEBUG_DEVELOPER);
echo '
';
echo "
';
}
}
/**
* Prints the form for setting a quiz' overall grade
*
* @param object $quiz The quiz object of the quiz in question
* @param object $pageurl The url of the current page with the parameters required
* for links returning to the current page, as a moodle_url object
* @param int $tabindex The tabindex to start from for the form elements created
* @return int The tabindex from which the calling page can continue, that is,
* the last value used +1.
*/
function quiz_print_grading_form($quiz, $pageurl, $tabindex) {
global $OUTPUT;
$strsave = get_string('save', 'quiz');
echo '
';
echo '';
echo "
\n";
return $tabindex + 1;
}
/**
* Print the status bar
*
* @param object $quiz The quiz object of the quiz in question
*/
function quiz_print_status_bar($quiz) {
global $DB;
$bits = array();
$bits[] = html_writer::tag('span',
get_string('totalmarksx', 'quiz', quiz_format_grade($quiz, $quiz->sumgrades)),
array('class' => 'totalpoints'));
$bits[] = html_writer::tag('span',
get_string('numquestionsx', 'quiz', $DB->count_records('quiz_slots', array('quizid' => $quiz->id))),
array('class' => 'numberofquestions'));
$timenow = time();
// Exact open and close dates for the tool-tip.
$dates = array();
if ($quiz->timeopen > 0) {
if ($timenow > $quiz->timeopen) {
$dates[] = get_string('quizopenedon', 'quiz', userdate($quiz->timeopen));
} else {
$dates[] = get_string('quizwillopen', 'quiz', userdate($quiz->timeopen));
}
}
if ($quiz->timeclose > 0) {
if ($timenow > $quiz->timeclose) {
$dates[] = get_string('quizclosed', 'quiz', userdate($quiz->timeclose));
} else {
$dates[] = get_string('quizcloseson', 'quiz', userdate($quiz->timeclose));
}
}
if (empty($dates)) {
$dates[] = get_string('alwaysavailable', 'quiz');
}
$tooltip = implode(', ', $dates);
// Brief summary on the page.
if ($timenow < $quiz->timeopen) {
$currentstatus = get_string('quizisclosedwillopen', 'quiz',
userdate($quiz->timeopen, get_string('strftimedatetimeshort', 'langconfig')));
} else if ($quiz->timeclose && $timenow <= $quiz->timeclose) {
$currentstatus = get_string('quizisopenwillclose', 'quiz',
userdate($quiz->timeclose, get_string('strftimedatetimeshort', 'langconfig')));
} else if ($quiz->timeclose && $timenow > $quiz->timeclose) {
$currentstatus = get_string('quizisclosed', 'quiz');
} else {
$currentstatus = get_string('quizisopen', 'quiz');
}
$bits[] = html_writer::tag('span', $currentstatus,
array('class' => 'quizopeningstatus', 'title' => implode(', ', $dates)));
echo html_writer::tag('div', implode(' | ', $bits), array('class' => 'statusbar'));
}