3 * Functions used to show question editing interface
5 * TODO: currently the function question_list still provides controls specific
6 * to the quiz module. This needs to be generalised.
8 * @author Martin Dougiamas and many others. This has recently been extensively
9 * rewritten by members of the Serving Mathematics project
10 * {@link http://maths.york.ac.uk/serving_maths}
11 * @license http://www.gnu.org/copyleft/gpl.html GNU Public License
12 * @package questionbank
15 require_once($CFG->libdir
.'/questionlib.php');
17 define('DEFAULT_QUESTIONS_PER_PAGE', 20);
19 function get_module_from_cmid($cmid){
21 if (!$cmrec = get_record_sql("SELECT cm.*, md.name as modname
22 FROM {$CFG->prefix}course_modules cm,
23 {$CFG->prefix}modules md
24 WHERE cm.id = '$cmid' AND
27 } elseif (!$modrec =get_record($cmrec->modname
, 'id', $cmrec->instance
)) {
30 $modrec->instance
= $modrec->id
;
31 $modrec->cmid
= $cmrec->id
;
33 return array($modrec, $cmrec);
36 * Function to read all questions for category into big array
38 * @param int $category category number
39 * @param bool $noparent if true only questions with NO parent will be selected
40 * @param bool $recurse include subdirectories
41 * @param bool $export set true if this is called by questionbank export
42 * @author added by Howard Miller June 2004
44 function get_questions_category( $category, $noparent=false, $recurse=true, $export=true ) {
48 // questions will be added to an array
51 // build sql bit for $noparent
54 $npsql = " and parent='0' ";
57 // get (list) of categories
59 $categorylist = question_categorylist( $category->id
);
62 $categorylist = $category->id
;
65 // get the list of questions for the category
66 if ($questions = get_records_select("question","category IN ($categorylist) $npsql", "qtype, name ASC")) {
68 // iterate through questions, getting stuff we need
69 foreach($questions as $question) {
70 $questiontype = $QTYPES[$question->qtype
];
71 $question->export_process
= $export;
72 $questiontype->get_question_options( $question );
73 $qresults[] = $question;
81 * Gets the default category in a course
83 * It returns the first category with no parent category. If no categories
84 * exist yet then one is created.
85 * @return object The default category
86 * @param integer $courseid The id of the course whose default category is wanted
88 function get_default_question_category($courseid) {
89 // If it already exists, just return it.
90 if ($category = get_records_select("question_categories", "course = '$courseid' AND parent = '0'", 'id', '*', '', 1)) {
91 return reset($category);
94 // Otherwise, we need to make one
95 $category = new stdClass
;
96 $category->name
= get_string("default", "quiz");
97 $category->info
= get_string("defaultinfo", "quiz");
98 $category->course
= $courseid;
99 $category->parent
= 0;
100 $category->sortorder
= 999; // By default, all categories get this number, and are sorted alphabetically.
101 $category->publish
= 0;
102 $category->stamp
= make_unique_id_code();
104 if (!$category->id
= insert_record("question_categories", $category)) {
105 notify("Error creating a default category!");
112 * prints a form to choose categories
114 function question_category_form($course, $pageurl, $current, $recurse=1, $showhidden=false, $showquestiontext=false) {
117 /// Make sure the default category exists for this course
118 get_default_question_category($course->id
);
120 /// Get all the existing categories now
121 $catmenu = question_category_options($course->id
, true);
123 $strcategory = get_string("category", "quiz");
124 $strshow = get_string("show", "quiz");
125 $streditcats = get_string("editcategories", "quiz");
127 popup_form ("edit.php?".$pageurl->get_query_string()."&category=", $catmenu, "catmenu", $current, "", "", "", false, "self", "<strong>$strcategory</strong>");
129 echo '<form method="get" action="edit.php" id="displayoptions">';
130 echo "<fieldset class='invisiblefieldset'>";
131 echo $pageurl->hidden_params_out(array('recurse', 'showhidden', 'showquestiontext'));
132 question_category_form_checkbox('recurse', $recurse);
133 question_category_form_checkbox('showhidden', $showhidden);
134 question_category_form_checkbox('showquestiontext', $showquestiontext);
135 echo '<noscript><div class="centerpara"><input type="submit" value="'. get_string('go') .'" />';
136 echo '</div></noscript></fieldset></form>';
140 * Private funciton to help the preceeding function.
142 function question_category_form_checkbox($name, $checked) {
143 echo '<div><input type="hidden" id="' . $name . '_off" name="' . $name . '" value="0" />';
144 echo '<input type="checkbox" id="' . $name . '_on" name="' . $name . '" value="1"';
146 echo ' checked="checked"';
148 echo ' onchange="getElementById(\'displayoptions\').submit(); return true;" />';
149 echo '<label for="' . $name . '_on">';
150 print_string($name, 'quiz');
151 echo "</label></div>\n";
155 * Prints the table of questions in a category with interactions
157 * @param object $course The course object
158 * @param int $categoryid The id of the question category to be displayed
159 * @param int $cm The course module record if we are in the context of a particular module, 0 otherwise
160 * @param int $recurse This is 1 if subcategories should be included, 0 otherwise
161 * @param int $page The number of the page to be displayed
162 * @param int $perpage Number of questions to show per page
163 * @param boolean $showhidden True if also hidden questions should be displayed
164 * @param boolean $showquestiontext whether the text of each question should be shown in the list
166 function question_list($course, $pageurl, $categoryid, $cm = null,
167 $recurse=1, $page=0, $perpage=100, $showhidden=false, $sortorder='typename', $sortorderdecoded='qtype, name ASC',
168 $showquestiontext = false) {
170 global $QTYPE_MENU, $USER, $CFG, $THEME;
172 $strcategory = get_string("category", "quiz");
173 $strquestion = get_string("question", "quiz");
174 $straddquestions = get_string("addquestions", "quiz");
175 $strimportquestions = get_string("importquestions", "quiz");
176 $strexportquestions = get_string("exportquestions", "quiz");
177 $strnoquestions = get_string("noquestions", "quiz");
178 $strselect = get_string("select", "quiz");
179 $strselectall = get_string("selectall", "quiz");
180 $strselectnone = get_string("selectnone", "quiz");
181 $strcreatenewquestion = get_string("createnewquestion", "quiz");
182 $strquestionname = get_string("questionname", "quiz");
183 $strdelete = get_string("delete");
184 $stredit = get_string("edit");
185 $straction = get_string("action");
186 $strrestore = get_string('restore');
188 $strtype = get_string("type", "quiz");
189 $strcreatemultiple = get_string("createmultiple", "quiz");
190 $strpreview = get_string("preview","quiz");
193 echo "<p style=\"text-align:center;\"><b>";
194 print_string("selectcategoryabove", "quiz");
199 if (!$category = get_record('question_categories', 'id', $categoryid)) {
200 notify('Category not found!');
203 $canedit = has_capability('moodle/question:manage', get_context_instance(CONTEXT_COURSE
, $category->course
));
205 if ($cm AND $cm->modname
== 'quiz') {
206 $quizid = $cm->instance
;
211 echo '<div class="boxaligncenter">';
212 $formatoptions = new stdClass
;
213 $formatoptions->noclean
= true;
214 echo format_text($category->info
, FORMAT_MOODLE
, $formatoptions, $course->id
);
218 // check if editing questions in this category is allowed
220 echo '<td valign="top" align="right">';
221 $returnurl = urlencode($pageurl->out());
222 $questionurl = new moodle_url("$CFG->wwwroot/question/question.php",
223 array('returnurl' => $returnurl,
224 'category' => $category->id
));
226 $questionurl->param('cmid', $cm->id
);
228 popup_form ($questionurl->out().'&qtype=', $QTYPE_MENU, "addquestion", "", "choose", "", "", false, "self", "<strong>$strcreatenewquestion</strong>");
229 echo '</td><td valign="top" align="right">';
230 helpbutton("questiontypes", $strcreatenewquestion, "quiz");
235 print_string("publishedit","quiz");
239 echo '</tr></table>';
242 $categorylist = ($recurse) ?
question_categorylist($category->id
) : $category->id
;
245 $showhidden = $showhidden ?
'' : " AND hidden = '0'";
247 if (!$totalnumber = count_records_select('question', "category IN ($categorylist) AND parent = '0' $showhidden")) {
248 echo "<p style=\"text-align:center;\">";
249 print_string("noquestions", "quiz");
254 if (!$questions = get_records_select('question', "category IN ($categorylist) AND parent = '0' $showhidden", $sortorderdecoded, '*', $page*$perpage, $perpage)) {
255 // There are no questions on the requested page.
257 if (!$questions = get_records_select('question', "category IN ($categorylist) AND parent = '0' $showhidden", $sortorderdecoded, '*', 0, $perpage)) {
258 // There are no questions at all
259 echo "<p style=\"text-align:center;\">";
260 print_string("noquestions", "quiz");
266 print_paging_bar($totalnumber, $page, $perpage, $pageurl, 'qpage');
268 echo '<form method="post" action="edit.php">';
269 echo '<fieldset class="invisiblefieldset" style="display: block;">';
270 echo '<input type="hidden" name="sesskey" value="'.$USER->sesskey
.'" />';
271 echo $pageurl->hidden_params_out(array('qsortorder'));
272 echo '<table id="categoryquestions" style="width: 100%"><tr>';
273 echo "<th style=\"white-space:nowrap;\" class=\"header\" scope=\"col\">$straction</th>";
275 $sortoptions = array('alpha' => get_string("sortalpha", "quiz"),
276 'typealpha' => get_string("sorttypealpha", "quiz"),
277 'age' => get_string("sortage", "quiz"));
278 $orderselect = choose_from_menu ($sortoptions, 'qsortorder', $sortorder, false, 'this.form.submit();', '0', true);
279 $orderselect .= '<noscript><div><input type="submit" value="'.get_string("sortsubmit", "quiz").'" /></div></noscript>';
280 echo "<th style=\"white-space:nowrap; text-align: left;\" class=\"header\" scope=\"col\">$strquestionname $orderselect</th>
281 <th style=\"white-space:nowrap; text-align: right;\" class=\"header\" scope=\"col\">$strtype</th>";
283 foreach ($questions as $question) {
286 if ($question->hidden
) {
287 $nameclass = 'dimmed_text';
288 $textclass = 'dimmed_text';
290 if ($showquestiontext) {
291 $nameclass .= ' header';
294 $nameclass = 'class="' . $nameclass . '"';
297 $textclass = 'class="' . $textclass . '"';
300 echo "<tr>\n<td style=\"white-space:nowrap;\" $nameclass>\n";
302 if (function_exists('module_specific_actions')) {
303 echo module_specific_actions($pageurl, $question->id
, $cm->id
);
307 link_to_popup_window('/question/preview.php?id=' . $question->id
. '&quizid=' . $quizid, 'questionpreview',
308 "<img src=\"$CFG->pixpath/t/preview.gif\" class=\"iconsmall\" alt=\"$strpreview\" />",
309 0, 0, $strpreview, QUESTION_PREVIEW_POPUP_OPTIONS
);
311 // edit, hide, delete question, using question capabilities, not quiz capabilieies
313 $questionparams = (($cm !== null)?
array('cmid' => $cm->id
) : array()) +
314 (array('returnurl' => $pageurl->out(), 'id'=>$question->id
));
315 $questionurl = new moodle_url("$CFG->wwwroot/question/question.php", $questionparams);
316 echo "<a title=\"$stredit\" href=\"".$questionurl->out()."\"><img
317 src=\"$CFG->pixpath/t/edit.gif\" alt=\"$stredit\" /></a> ";
319 if($question->hidden
) {
320 echo "<a title=\"$strrestore\" href=\"edit.php?".$pageurl->get_query_string()."&unhide=$question->id&sesskey=$USER->sesskey\"><img
321 src=\"$CFG->pixpath/t/restore.gif\" alt=\"$strrestore\" /></a>";
323 echo "<a title=\"$strdelete\" href=\"edit.php?".$pageurl->get_query_string()."&deleteselected=$question->id&q$question->id=1\"><img
324 src=\"$CFG->pixpath/t/delete.gif\" alt=\"$strdelete\" /></a>";
327 echo " <input title=\"$strselect\" type=\"checkbox\" name=\"q$question->id\" value=\"1\" />";
330 echo "<td $nameclass>" . format_string($question->name
) . "</td>\n";
331 echo "<td $nameclass style='text-align: right'>\n";
332 print_question_icon($question);
335 if($showquestiontext){
336 echo '<tr><td colspan="3" ' . $textclass . '>';
337 $formatoptions = new stdClass
;
338 $formatoptions->noclean
= true;
339 $formatoptions->para
= false;
340 echo format_text($question->questiontext
, $question->questiontextformat
,
341 $formatoptions, $course->id
);
347 $paging = print_paging_bar($totalnumber, $page, $perpage, $pageurl, 'qpage',
349 if ($totalnumber > DEFAULT_QUESTIONS_PER_PAGE
) {
350 if ($perpage == DEFAULT_QUESTIONS_PER_PAGE
) {
351 $showall = '<a href="edit.php?'.$pageurl->get_query_string(array('qperpage'=>1000)).'">'.get_string('showall', 'moodle', $totalnumber).'</a>';
353 $showall = '<a href="edit.php?'.$pageurl->get_query_string(array('qperpage'=>DEFAULT_QUESTIONS_PER_PAGE
)).'">'.get_string('showperpage', 'moodle', DEFAULT_QUESTIONS_PER_PAGE
).'</a>';
356 $paging = substr($paging, 0, strrpos($paging, '</div>'));
357 $paging .= "<br />$showall</div>";
359 $paging = "<div class='paging'>$showall</div>";
364 echo '<table class="quiz-edit-selected"><tr><td colspan="2">';
365 echo '<a href="javascript:select_all_in(\'TABLE\', null, \'categoryquestions\');">'.$strselectall.'</a> /'.
366 ' <a href="javascript:deselect_all_in(\'TABLE\', null, \'categoryquestions\');">'.$strselectnone.'</a>'.
367 '</td><td align="right"><b> '.get_string('withselected', 'quiz').':</b></td></tr><tr><td>';
369 if (function_exists('module_specific_buttons')) {
370 echo module_specific_buttons($cm->id
);
372 // print delete and move selected question
374 echo '<input type="submit" name="deleteselected" value="'.$strdelete."\" /></td><td>\n";
375 echo '<input type="submit" name="move" value="'.get_string('moveto', 'quiz')."\" />\n";
376 question_category_select_menu($course->id
, false, true, $category->id
);
378 echo "</td></tr></table>";
380 if (function_exists('module_specific_controls')) {
381 echo module_specific_controls($totalnumber, $recurse, $category->id
, $cm->id
);
387 * Shows the question bank editing interface.
389 * The function also processes a number of actions:
391 * Actions affecting the question pool:
392 * move Moves a question to a different category
393 * deleteselected Deletes the selected questions from the category
395 * category Chooses the category
396 * displayoptions Sets display options
398 * @author Martin Dougiamas and many others. This has recently been extensively
399 * rewritten by Gustav Delius and other members of the Serving Mathematics project
400 * {@link http://maths.york.ac.uk/serving_maths}
401 * @param moodle_url $pageurl object representing this pages url.
403 function question_showbank($pageurl, $cm, $page, $perpage, $sortorder, $sortorderdecoded, $cat, $recurse, $showhidden, $showquestiontext){
404 global $COURSE, $USER;
406 /// Now, check for commands on this page and modify variables as necessary
407 if (isset($_REQUEST['move']) and confirm_sesskey()) { /// Move selected questions to new category
408 $tocategoryid = required_param('category', PARAM_INT
);
409 if (!$tocategory = get_record('question_categories', 'id', $tocategoryid)) {
410 error('Invalid category');
412 if (!has_capability('moodle/question:managecategory', get_context_instance(CONTEXT_COURSE
, $tocategory->course
))){
413 error(get_string('categorynoedit', 'quiz', $tocategory->name
), $pageurl->out());
415 foreach ($_POST as $key => $value) { // Parse input for question ids
416 if (preg_match('!^q([0-9]+)$!', $key, $matches)) {
418 if (!set_field('question', 'category', $tocategory->id
, 'id', $key)) {
419 error('Could not update category field');
425 if (isset($_REQUEST['deleteselected'])) { // delete selected questions from the category
427 if (isset($_REQUEST['confirm']) and confirm_sesskey()) { // teacher has already confirmed the action
428 $deleteselected = required_param('deleteselected');
429 if ($_REQUEST['confirm'] == md5($deleteselected)) {
430 if ($questionlist = explode(',', $deleteselected)) {
431 // for each question either hide it if it is in use or delete it
432 foreach ($questionlist as $questionid) {
433 if (record_exists('quiz_question_instances', 'question', $questionid) or
434 record_exists('question_states', 'originalquestion', $questionid)) {
435 if (!set_field('question', 'hidden', 1, 'id', $questionid)) {
436 error('Was not able to hide question');
439 delete_question($questionid);
446 redirect($pageurl->out());
448 error("Confirmation string was incorrect");
451 } else { // teacher still has to confirm
452 // make a list of all the questions that are selected
453 $rawquestions = $_REQUEST;
454 $questionlist = ''; // comma separated list of ids of questions to be deleted
455 $questionnames = ''; // string with names of questions separated by <br /> with
456 // an asterix in front of those that are in use
457 $inuse = false; // set to true if at least one of the questions is in use
458 foreach ($rawquestions as $key => $value) { // Parse input for question ids
459 if (preg_match('!^q([0-9]+)$!', $key, $matches)) {
460 $key = $matches[1]; $questionlist .= $key.',';
461 if (record_exists('quiz_question_instances', 'question', $key) or
462 record_exists('question_states', 'originalquestion', $key)) {
463 $questionnames .= '* ';
466 $questionnames .= get_field('question', 'name', 'id', $key).'<br />';
469 if (!$questionlist) { // no questions were selected
470 redirect($pageurl->out());
472 $questionlist = rtrim($questionlist, ',');
474 // Add an explanation about questions in use
476 $questionnames .= '<br />'.get_string('questionsinuse', 'quiz');
478 notice_yesno(get_string("deletequestionscheck", "quiz", $questionnames),
479 $pageurl->out(), $pageurl->out(),
480 array('sesskey' => $USER->sesskey
, 'deleteselected' => $questionlist, 'confirm' => md5($questionlist)),
481 NULL, 'post', 'get');
485 print_footer($COURSE);
491 if(isset($_REQUEST['unhide']) && confirm_sesskey()) {
492 $unhide = required_param('unhide', PARAM_INT
);
493 if(!set_field('question', 'hidden', 0, 'id', $unhide)) {
494 error("Failed to unhide the question.");
496 redirect($pageurl->out());
499 // starts with category selection form
500 print_box_start('generalbox questionbank');
501 print_heading(get_string('questionbank', 'question'), '', 2);
502 question_category_form($COURSE, $pageurl, $cat, $recurse,
503 $showhidden, $showquestiontext);
505 // continues with list of questions
506 question_list($COURSE, $pageurl, $cat, isset($cm) ?
$cm : null,
507 $recurse, $page, $perpage, $showhidden, $sortorder, $sortorderdecoded,
513 * Common setup for all pages for editing questions.
514 * @param boolean $requirecmid require cmid? default false
515 * @param boolean $requirecourseid require courseid, if cmid is not given? default true
516 * @return array $thispageurl, $courseid, $cmid, $cm, $module, $pagevars
518 function question_edit_setup($requirecmid = false, $requirecourseid = true){
520 //$thispageurl is used to construct urls for all question edit pages we link to from this page. It contains an array
521 //of parameters that are passed from page to page.
522 $thispageurl = new moodle_url();
524 $cmid =required_param('cmid', PARAM_INT
);
526 $cmid = optional_param('cmid', 0, PARAM_INT
);
529 list($module, $cm) = get_module_from_cmid($cmid);
530 $courseid = $cm->course
;
531 $thispageurl->params(compact('cmid'));
535 if ($requirecourseid){
536 $courseid = required_param('courseid', PARAM_INT
);
538 $courseid = optional_param('courseid', 0, PARAM_INT
);
541 $thispageurl->params(compact('courseid'));
544 require_login($courseid, false);
547 $pagevars['qpage'] = optional_param('qpage', -1, PARAM_INT
);
549 //pass 'cat' from page to page and when 'category' comes from a drop down menu
550 //then we also reset the qpage so we go to page 1 of
552 $pagevars['cat'] = optional_param('cat', 0, PARAM_INT
);
553 if ($category = optional_param('category', 0, PARAM_INT
)){
554 $pagevars['cat'] = $category;
555 $pagevars['qpage'] = 0;
557 if ($pagevars['cat']){
558 $thispageurl->param('cat', $pagevars['cat']);
560 if ($pagevars['qpage'] > -1) {
561 $thispageurl->param('qpage', $pagevars['qpage']);
563 $pagevars['qpage'] = 0;
566 $pagevars['qperpage'] = optional_param('qperpage', -1, PARAM_INT
);
567 if ($pagevars['qperpage'] > -1) {
568 $thispageurl->param('qperpage', $pagevars['qperpage']);
570 $pagevars['qperpage'] = DEFAULT_QUESTIONS_PER_PAGE
;
573 $sortoptions = array('alpha' => 'name, qtype ASC',
574 'typealpha' => 'qtype, name ASC',
577 if ($sortorder = optional_param('qsortorder', '', PARAM_ALPHA
)) {
578 $pagevars['qsortorderdecoded'] = $sortoptions[$sortorder];
579 $pagevars['qsortorder'] = $sortorder;
580 $thispageurl->param('qsortorder', $sortorder);
582 $pagevars['qsortorderdecoded'] = $sortoptions['typealpha'];
583 $pagevars['qsortorder'] = 'typealpha';
587 if (empty($pagevars['cat']) or !count_records_select("question_categories", "id = '".$pagevars['cat']."' AND (course = '{$COURSE->id}' OR publish = '1')")) {
588 $category = get_default_question_category($COURSE->id
);
589 $pagevars['cat'] = $category->id
;
590 $thispageurl->param('cat', $category->id
);
593 if(($recurse = optional_param('recurse', -1, PARAM_BOOL
)) != -1) {
594 $pagevars['recurse'] = $recurse;
595 $thispageurl->param('recurse', $recurse);
597 $pagevars['recurse'] = 1;
600 if(($showhidden = optional_param('showhidden', -1, PARAM_BOOL
)) != -1) {
601 $pagevars['showhidden'] = $showhidden;
602 $thispageurl->param('showhidden', $showhidden);
604 $pagevars['showhidden'] = 0;
607 if(($showquestiontext = optional_param('showquestiontext', -1, PARAM_BOOL
)) != -1) {
608 $pagevars['showquestiontext'] = $showquestiontext;
609 $thispageurl->param('showquestiontext', $showquestiontext);
611 $pagevars['showquestiontext'] = 0;
615 $pagevars['cpage'] = optional_param('cpage', 1, PARAM_INT
);
616 if ($pagevars['cpage'] != 1){
617 $thispageurl->param('cpage', $pagevars['cpage']);
621 return array($thispageurl, $courseid, $cmid, $cm, $module, $pagevars);