listlib: MDL-17422 Paging in listlib was badly screwed
[moodle.git] / question / editlib.php
CommitLineData
516cf3eb 1<?php // $Id$
2/**
b72ff476 3 * Functions used to show question editing interface
4323d029 4 *
4323d029 5 *
6 * @author Martin Dougiamas and many others. This has recently been extensively
7 * rewritten by members of the Serving Mathematics project
8 * {@link http://maths.york.ac.uk/serving_maths}
9 * @license http://www.gnu.org/copyleft/gpl.html GNU Public License
10 * @package questionbank
11 */
516cf3eb 12
4fbfd971 13require_once($CFG->libdir.'/questionlib.php');
516cf3eb 14
f92cf442 15define('DEFAULT_QUESTIONS_PER_PAGE', 20);
16
86909ce0 17function get_module_from_cmid($cmid){
f34488b2 18 global $CFG, $DB;
19 if (!$cmrec = $DB->get_record_sql("SELECT cm.*, md.name as modname
20 FROM {course_modules} cm,
21 {modules} md
22 WHERE cm.id = ? AND
23 md.id = cm.module", array($cmid))){
1eda5201 24 print_error('invalidcoursemodule');
f34488b2 25 } elseif (!$modrec =$DB->get_record($cmrec->modname, array('id' => $cmrec->instance))) {
1eda5201 26 print_error('invalidcoursemodule');
86909ce0 27 }
28 $modrec->instance = $modrec->id;
d0e88092 29 $modrec->cmid = $cmrec->id;
ea16c547 30 $cmrec->name = $modrec->name;
271e6dec 31
86909ce0 32 return array($modrec, $cmrec);
33}
4fbfd971 34/**
35* Function to read all questions for category into big array
36*
37* @param int $category category number
36e2232e 38* @param bool $noparent if true only questions with NO parent will be selected
39* @param bool $recurse include subdirectories
5fd8f999 40* @param bool $export set true if this is called by questionbank export
4fbfd971 41* @author added by Howard Miller June 2004
42*/
5fd8f999 43function get_questions_category( $category, $noparent=false, $recurse=true, $export=true ) {
4fbfd971 44
f34488b2 45 global $QTYPES, $DB;
4fbfd971 46
47 // questions will be added to an array
48 $qresults = array();
49
50 // build sql bit for $noparent
51 $npsql = '';
52 if ($noparent) {
53 $npsql = " and parent='0' ";
54 }
55
36e2232e 56 // get (list) of categories
57 if ($recurse) {
58 $categorylist = question_categorylist( $category->id );
59 }
60 else {
61 $categorylist = $category->id;
62 }
63
4fbfd971 64 // get the list of questions for the category
f34488b2 65 list ($usql, $params) = $DB->get_in_or_equal(explode(',', $categorylist));
66 if ($questions = $DB->get_records_select("question","category $usql $npsql", $params, "qtype, name ASC")) {
4fbfd971 67
68 // iterate through questions, getting stuff we need
69 foreach($questions as $question) {
70 $questiontype = $QTYPES[$question->qtype];
5fd8f999 71 $question->export_process = $export;
4fbfd971 72 $questiontype->get_question_options( $question );
73 $qresults[] = $question;
74 }
75 }
76
77 return $qresults;
78}
79
4fbfd971 80
271e6dec 81function question_can_delete_cat($todelete){
f34488b2 82 global $CFG, $DB;
83 $record = $DB->get_record_sql("SELECT count(*) as count, c1.contextid as contextid FROM {question_categories} c1,
84 {question_categories} c2 WHERE c2.id = ?
85 AND c1.contextid = c2.contextid GROUP BY c1.contextid", array($todelete));
271e6dec 86 $contextid = $record->contextid;
87 $count = $record->count;
88 if ($count < 2) {
ac93d63d 89 print_error('cannotdeletecate', 'question');
271e6dec 90 } else {
91 require_capability('moodle/question:managecategory', get_context_instance_by_id($contextid));
92 }
93}
4fbfd971 94/**
95 * prints a form to choose categories
96 */
271e6dec 97function question_category_form($contexts, $pageurl, $current, $recurse=1, $showhidden=false, $showquestiontext=false) {
e586cfb4 98 global $CFG;
516cf3eb 99
516cf3eb 100
101/// Get all the existing categories now
271e6dec 102 $catmenu = question_category_options($contexts, false, 0, true);
dcd51df2 103
271e6dec 104 $strcategory = get_string('category', 'quiz');
105 $strshow = get_string('show', 'quiz');
106 $streditcats = get_string('editcategories', 'quiz');
516cf3eb 107
271e6dec 108 popup_form ('edit.php?'.$pageurl->get_query_string().'&amp;category=', $catmenu, 'catmenu', $current, '', '', '', false, 'self', "<strong>$strcategory</strong>");
0fd5feef 109
d1f2b9e1 110 echo '<form method="get" action="edit.php" id="displayoptions">';
0fd5feef 111 echo "<fieldset class='invisiblefieldset'>";
36e298bc 112 echo $pageurl->hidden_params_out(array('recurse', 'showhidden', 'showquestiontext'));
624cbc9c 113 question_category_form_checkbox('recurse', $recurse);
114 question_category_form_checkbox('showhidden', $showhidden);
115 question_category_form_checkbox('showquestiontext', $showquestiontext);
116 echo '<noscript><div class="centerpara"><input type="submit" value="'. get_string('go') .'" />';
117 echo '</div></noscript></fieldset></form>';
118}
119
120/**
121 * Private funciton to help the preceeding function.
122 */
123function question_category_form_checkbox($name, $checked) {
124 echo '<div><input type="hidden" id="' . $name . '_off" name="' . $name . '" value="0" />';
125 echo '<input type="checkbox" id="' . $name . '_on" name="' . $name . '" value="1"';
126 if ($checked) {
516cf3eb 127 echo ' checked="checked"';
128 }
d2ce367f 129 echo ' onchange="getElementById(\'displayoptions\').submit(); return true;" />';
624cbc9c 130 echo '<label for="' . $name . '_on">';
131 print_string($name, 'quiz');
132 echo "</label></div>\n";
516cf3eb 133}
134
516cf3eb 135/**
136* Prints the table of questions in a category with interactions
137*
138* @param object $course The course object
139* @param int $categoryid The id of the question category to be displayed
86909ce0 140* @param int $cm The course module record if we are in the context of a particular module, 0 otherwise
516cf3eb 141* @param int $recurse This is 1 if subcategories should be included, 0 otherwise
142* @param int $page The number of the page to be displayed
143* @param int $perpage Number of questions to show per page
144* @param boolean $showhidden True if also hidden questions should be displayed
dcc2ffde 145* @param boolean $showquestiontext whether the text of each question should be shown in the list
516cf3eb 146*/
271e6dec 147function question_list($contexts, $pageurl, $categoryandcontext, $cm = null,
36e298bc 148 $recurse=1, $page=0, $perpage=100, $showhidden=false, $sortorder='typename', $sortorderdecoded='qtype, name ASC',
271e6dec 149 $showquestiontext = false, $addcontexts = array()) {
f34488b2 150 global $USER, $CFG, $THEME, $COURSE, $DB;
271e6dec 151
152 list($categoryid, $contextid)= explode(',', $categoryandcontext);
153
e2ae84a2 154 $qtypemenu = question_type_menu();
335768f4 155
516cf3eb 156 $strcategory = get_string("category", "quiz");
157 $strquestion = get_string("question", "quiz");
158 $straddquestions = get_string("addquestions", "quiz");
159 $strimportquestions = get_string("importquestions", "quiz");
160 $strexportquestions = get_string("exportquestions", "quiz");
fa583f5f 161 $strnoquestions = get_string("noquestionsincategory", "quiz");
516cf3eb 162 $strselect = get_string("select", "quiz");
163 $strselectall = get_string("selectall", "quiz");
164 $strselectnone = get_string("selectnone", "quiz");
165 $strcreatenewquestion = get_string("createnewquestion", "quiz");
166 $strquestionname = get_string("questionname", "quiz");
167 $strdelete = get_string("delete");
168 $stredit = get_string("edit");
271e6dec 169 $strmove = get_string('moveqtoanothercontext', 'question');
170 $strview = get_string("view");
516cf3eb 171 $straction = get_string("action");
172 $strrestore = get_string('restore');
173
516cf3eb 174 $strtype = get_string("type", "quiz");
175 $strcreatemultiple = get_string("createmultiple", "quiz");
176 $strpreview = get_string("preview","quiz");
177
178 if (!$categoryid) {
0fd5feef 179 echo "<p style=\"text-align:center;\"><b>";
516cf3eb 180 print_string("selectcategoryabove", "quiz");
181 echo "</b></p>";
516cf3eb 182 return;
183 }
184
f34488b2 185 if (!$category = $DB->get_record('question_categories', array('id' => $categoryid, 'contextid' => $contextid))) {
dcc2ffde 186 notify('Category not found!');
516cf3eb 187 return;
188 }
271e6dec 189 $catcontext = get_context_instance_by_id($contextid);
190 $canadd = has_capability('moodle/question:add', $catcontext);
191 //check for capabilities on all questions in category, will also apply to sub cats.
192 $caneditall =has_capability('moodle/question:editall', $catcontext);
193 $canuseall =has_capability('moodle/question:useall', $catcontext);
194 $canmoveall =has_capability('moodle/question:moveall', $catcontext);
86909ce0 195
196 if ($cm AND $cm->modname == 'quiz') {
86909ce0 197 $quizid = $cm->instance;
198 } else {
86909ce0 199 $quizid = 0;
dcc2ffde 200 }
271e6dec 201 $returnurl = $pageurl->out();
202 $questionurl = new moodle_url("$CFG->wwwroot/question/question.php",
203 array('returnurl' => $returnurl));
204 if ($cm!==null){
205 $questionurl->param('cmid', $cm->id);
206 } else {
207 $questionurl->param('courseid', $COURSE->id);
208 }
209 $questionmoveurl = new moodle_url("$CFG->wwwroot/question/contextmoveq.php",
210 array('returnurl' => $returnurl));
211 if ($cm!==null){
212 $questionmoveurl->param('cmid', $cm->id);
213 } else {
214 $questionmoveurl->param('courseid', $COURSE->id);
215 }
09275894 216 echo '<div class="boxaligncenter">';
4abc23b2 217 $formatoptions = new stdClass;
7347c60b 218 $formatoptions->noclean = true;
271e6dec 219 echo format_text($category->info, FORMAT_MOODLE, $formatoptions, $COURSE->id);
516cf3eb 220
221 echo '<table><tr>';
222
271e6dec 223 if ($canadd) {
516cf3eb 224 echo '<td valign="top" align="right">';
271e6dec 225 popup_form ($questionurl->out(false, array('category' => $category->id)).'&amp;qtype=', $qtypemenu, "addquestion", "", "choose", "", "", false, "self", "<strong>$strcreatenewquestion</strong>");
624cbc9c 226 echo '</td><td valign="top" align="right">';
516cf3eb 227 helpbutton("questiontypes", $strcreatenewquestion, "quiz");
dcc2ffde 228 echo '</td>';
516cf3eb 229 }
230 else {
dcc2ffde 231 echo '<td>';
271e6dec 232 print_string('nopermissionadd', 'question');
dcc2ffde 233 echo '</td>';
516cf3eb 234 }
235
dcc2ffde 236 echo '</tr></table>';
09275894 237 echo '</div>';
516cf3eb 238
dc1f00de 239 $categorylist = ($recurse) ? question_categorylist($category->id) : $category->id;
516cf3eb 240
241 // hide-feature
242 $showhidden = $showhidden ? '' : " AND hidden = '0'";
f34488b2 243 $categorylist_array = explode(',', $categorylist);
244 list($usql, $params) = $DB->get_in_or_equal($categorylist_array);
245 if (!$totalnumber = $DB->count_records_select('question', "category $usql AND parent = '0' $showhidden", $params)) {
0fd5feef 246 echo "<p style=\"text-align:center;\">";
fa583f5f 247 echo $strnoquestions;
516cf3eb 248 echo "</p>";
249 return;
250 }
251
f34488b2 252 if (!$questions = $DB->get_records_select('question', "category $usql AND parent = '0' $showhidden", $params, $sortorderdecoded, '*', $page*$perpage, $perpage)) {
516cf3eb 253 // There are no questions on the requested page.
254 $page = 0;
f34488b2 255 if (!$questions = $DB->get_records_select('question', "category $usql AND parent = '0' $showhidden", $params, $sortorderdecoded, '*', 0, $perpage)) {
516cf3eb 256 // There are no questions at all
0fd5feef 257 echo "<p style=\"text-align:center;\">";
fa583f5f 258 echo $strnoquestions;
516cf3eb 259 echo "</p>";
260 return;
261 }
262 }
263
b72ff476 264 print_paging_bar($totalnumber, $page, $perpage, $pageurl, 'qpage');
271e6dec 265 echo question_sort_options($pageurl, $sortorder);
266
267
86909ce0 268 echo '<form method="post" action="edit.php">';
624cbc9c 269 echo '<fieldset class="invisiblefieldset" style="display: block;">';
516cf3eb 270 echo '<input type="hidden" name="sesskey" value="'.$USER->sesskey.'" />';
987c5893 271 echo $pageurl->hidden_params_out();
624cbc9c 272 echo '<table id="categoryquestions" style="width: 100%"><tr>';
273 echo "<th style=\"white-space:nowrap;\" class=\"header\" scope=\"col\">$straction</th>";
271e6dec 274
275 echo "<th style=\"white-space:nowrap; text-align: left;\" class=\"header\" scope=\"col\">$strquestionname</th>
624cbc9c 276 <th style=\"white-space:nowrap; text-align: right;\" class=\"header\" scope=\"col\">$strtype</th>";
516cf3eb 277 echo "</tr>\n";
278 foreach ($questions as $question) {
624cbc9c 279 $nameclass = '';
280 $textclass = '';
281 if ($question->hidden) {
282 $nameclass = 'dimmed_text';
283 $textclass = 'dimmed_text';
284 }
285 if ($showquestiontext) {
286 $nameclass .= ' header';
287 }
288 if ($nameclass) {
289 $nameclass = 'class="' . $nameclass . '"';
290 }
291 if ($textclass) {
292 $textclass = 'class="' . $textclass . '"';
293 }
271e6dec 294
624cbc9c 295 echo "<tr>\n<td style=\"white-space:nowrap;\" $nameclass>\n";
271e6dec 296
297 $canuseq = question_has_capability_on($question, 'use', $question->category);
85c375c3 298 if (function_exists('module_specific_actions')) {
271e6dec 299 echo module_specific_actions($pageurl, $question->id, $cm->id, $canuseq);
516cf3eb 300 }
271e6dec 301
3765fd53 302 // preview
271e6dec 303 if ($canuseq) {
e7e62d45 304 $quizorcourseid = $quizid?('&amp;quizid=' . $quizid):('&amp;courseid=' .$COURSE->id);
305 link_to_popup_window('/question/preview.php?id=' . $question->id . $quizorcourseid, 'questionpreview',
271e6dec 306 "<img src=\"$CFG->pixpath/t/preview.gif\" class=\"iconsmall\" alt=\"$strpreview\" />",
307 0, 0, $strpreview, QUESTION_PREVIEW_POPUP_OPTIONS);
308 }
3765fd53 309 // edit, hide, delete question, using question capabilities, not quiz capabilieies
271e6dec 310 if (question_has_capability_on($question, 'edit', $question->category) || question_has_capability_on($question, 'move', $question->category)) {
311 echo "<a title=\"$stredit\" href=\"".$questionurl->out(false, array('id'=>$question->id))."\"><img
0fd5feef 312 src=\"$CFG->pixpath/t/edit.gif\" alt=\"$stredit\" /></a>&nbsp;";
271e6dec 313 } elseif (question_has_capability_on($question, 'view', $question->category)){
314 echo "<a title=\"$strview\" href=\"".$questionurl->out(false, array('id'=>$question->id))."\"><img
315 src=\"$CFG->pixpath/i/info.gif\" alt=\"$strview\" /></a>&nbsp;";
316 }
317
318 if (question_has_capability_on($question, 'move', $question->category) && question_has_capability_on($question, 'view', $question->category)) {
319 echo "<a title=\"$strmove\" href=\"".$questionurl->out(false, array('id'=>$question->id, 'movecontext'=>1))."\"><img
320 src=\"$CFG->pixpath/t/move.gif\" alt=\"$strmove\" /></a>&nbsp;";
321 }
322
323 if (question_has_capability_on($question, 'edit', $question->category)) {
516cf3eb 324 // hide-feature
325 if($question->hidden) {
86909ce0 326 echo "<a title=\"$strrestore\" href=\"edit.php?".$pageurl->get_query_string()."&amp;unhide=$question->id&amp;sesskey=$USER->sesskey\"><img
0fd5feef 327 src=\"$CFG->pixpath/t/restore.gif\" alt=\"$strrestore\" /></a>";
516cf3eb 328 } else {
86909ce0 329 echo "<a title=\"$strdelete\" href=\"edit.php?".$pageurl->get_query_string()."&amp;deleteselected=$question->id&amp;q$question->id=1\"><img
0fd5feef 330 src=\"$CFG->pixpath/t/delete.gif\" alt=\"$strdelete\" /></a>";
516cf3eb 331 }
332 }
271e6dec 333 if ($caneditall || $canmoveall || $canuseall){
334 echo "&nbsp;<input title=\"$strselect\" type=\"checkbox\" name=\"q$question->id\" value=\"1\" />";
335 }
516cf3eb 336 echo "</td>\n";
337
70ed7667 338 echo "<td $nameclass>" . format_string($question->name) . "</td>\n";
624cbc9c 339 echo "<td $nameclass style='text-align: right'>\n";
dcc2ffde 340 print_question_icon($question);
516cf3eb 341 echo "</td>\n";
342 echo "</tr>\n";
624cbc9c 343 if($showquestiontext){
344 echo '<tr><td colspan="3" ' . $textclass . '>';
345 $formatoptions = new stdClass;
346 $formatoptions->noclean = true;
347 $formatoptions->para = false;
348 echo format_text($question->questiontext, $question->questiontextformat,
271e6dec 349 $formatoptions, $COURSE->id);
624cbc9c 350 echo "</td></tr>\n";
351 }
516cf3eb 352 }
624cbc9c 353 echo "</table>\n";
624cbc9c 354
271e6dec 355 $paging = print_paging_bar($totalnumber, $page, $perpage, $pageurl, 'qpage', false, true);
f92cf442 356 if ($totalnumber > DEFAULT_QUESTIONS_PER_PAGE) {
357 if ($perpage == DEFAULT_QUESTIONS_PER_PAGE) {
b72ff476 358 $showall = '<a href="edit.php?'.$pageurl->get_query_string(array('qperpage'=>1000)).'">'.get_string('showall', 'moodle', $totalnumber).'</a>';
f92cf442 359 } else {
b72ff476 360 $showall = '<a href="edit.php?'.$pageurl->get_query_string(array('qperpage'=>DEFAULT_QUESTIONS_PER_PAGE)).'">'.get_string('showperpage', 'moodle', DEFAULT_QUESTIONS_PER_PAGE).'</a>';
624cbc9c 361 }
362 if ($paging) {
363 $paging = substr($paging, 0, strrpos($paging, '</div>'));
364 $paging .= "<br />$showall</div>";
365 } else {
271e6dec 366 $paging = "<div class='paging'>$showall</div>";
f92cf442 367 }
3abfa3a0 368 }
624cbc9c 369 echo $paging;
516cf3eb 370
271e6dec 371 if ($caneditall || $canmoveall || $canuseall){
314fc083 372 echo '<a href="javascript:select_all_in(\'TABLE\',null,\'categoryquestions\');">'.$strselectall.'</a> /'.
373 ' <a href="javascript:deselect_all_in(\'TABLE\',null,\'categoryquestions\');">'.$strselectnone.'</a>';
271e6dec 374 echo '<br />';
375 echo '<strong>&nbsp;'.get_string('withselected', 'quiz').':</strong><br />';
95947ac9 376
271e6dec 377 if (function_exists('module_specific_buttons')) {
378 echo module_specific_buttons($cm->id);
379 }
380 // print delete and move selected question
381 if ($caneditall) {
382 echo '<input type="submit" name="deleteselected" value="'.$strdelete."\" />\n";
383 }
384 if ($canmoveall && count($addcontexts)) {
385 echo '<input type="submit" name="move" value="'.get_string('moveto', 'quiz')."\" />\n";
386 question_category_select_menu($addcontexts, false, 0, "$category->id,$category->contextid");
387 }
516cf3eb 388
271e6dec 389 if (function_exists('module_specific_controls') && $canuseall) {
390 echo module_specific_controls($totalnumber, $recurse, $category, $cm->id);
391 }
516cf3eb 392 }
09275894 393 echo '</fieldset>';
394 echo "</form>\n";
516cf3eb 395}
271e6dec 396function question_sort_options($pageurl, $sortorder){
397 global $USER;
398 //sort options
fa583f5f 399 $html = "<div class=\"mdl-align questionsortoptions\">";
400 // POST method should only be used for parameters that change data
401 // or if POST method has to be used, the user must be redirected immediately to
402 // non-POSTed page to not break the back button
403 $html .= '<form method="get" action="edit.php">';
271e6dec 404 $html .= '<fieldset class="invisiblefieldset" style="display: block;">';
405 $html .= '<input type="hidden" name="sesskey" value="'.$USER->sesskey.'" />';
406 $html .= $pageurl->hidden_params_out(array('qsortorder'));
fa583f5f 407 //choose_from_menu concatenates the form name with
408 //"menu" so the label is for menuqsortorder
409 $sortoptions = array('alpha' => get_string("qname", "quiz"),
410 'typealpha' => get_string("qtypename", "quiz"),
411 'age' => get_string("age", "quiz"));
412 $a = choose_from_menu ($sortoptions, 'qsortorder', $sortorder, false, 'this.form.submit();', '0', true);
413 $html .= '<label for="menuqsortorder">'.get_string('sortquestionsbyx', 'quiz', $a).'</label>';
271e6dec 414 $html .= '<noscript><div><input type="submit" value="'.get_string("sortsubmit", "quiz").'" /></div></noscript>';
415 $html .= '</fieldset>';
416 $html .= "</form>\n";
417 $html .= "</div>\n";
418 return $html;
419}
86909ce0 420
271e6dec 421function question_showbank_actions($pageurl, $cm){
f34488b2 422 global $CFG, $COURSE, $DB;
271e6dec 423 /// Now, check for commands on this page and modify variables as necessary
8e77884c 424 if (optional_param('move', false, PARAM_BOOL) and confirm_sesskey()) { /// Move selected questions to new category
271e6dec 425 $category = required_param('category', PARAM_SEQUENCE);
426 list($tocategoryid, $contextid) = explode(',', $category);
f34488b2 427 if (! $tocategory = $DB->get_record('question_categories', array('id' => $tocategoryid, 'contextid' => $contextid))) {
ac93d63d 428 print_error('cannotfindcate', 'question');
86909ce0 429 }
271e6dec 430 $tocontext = get_context_instance_by_id($contextid);
431 require_capability('moodle/question:add', $tocontext);
8e77884c 432 $rawdata = (array) data_submitted();
271e6dec 433 $questionids = array();
8e77884c 434 foreach ($rawdata as $key => $value) { // Parse input for question ids
9ab38475 435 if (preg_match('!^q([0-9]+)$!', $key, $matches)) {
b72ff476 436 $key = $matches[1];
271e6dec 437 $questionids[] = $key;
438 }
439 }
440 if ($questionids){
f34488b2 441 list($usql, $params) = $DB->get_in_or_equal($questionids);
442 $sql = "SELECT q.*, c.contextid FROM {question} q, {question_categories} c WHERE q.id $usql AND c.id = q.category";
443 if (!$questions = $DB->get_records_sql($sql, $params)){
271e6dec 444 print_error('questiondoesnotexist', 'question', $pageurl->out());
445 }
446 $checkforfiles = false;
447 foreach ($questions as $question){
448 //check capabilities
449 question_require_capability_on($question, 'move');
450 $fromcontext = get_context_instance_by_id($question->contextid);
451 if (get_filesdir_from_context($fromcontext) != get_filesdir_from_context($tocontext)){
452 $checkforfiles = true;
453 }
454 }
455 $returnurl = $pageurl->out(false, array('category'=>"$tocategoryid,$contextid"));
456 if (!$checkforfiles){
7fb1b88d 457 if (!question_move_questions_to_category(implode(',', $questionids), $tocategory->id)) {
458 print_error('errormovingquestions', 'question', $returnurl, $questionids);
271e6dec 459 }
460 redirect($returnurl);
461 } else {
462 $movecontexturl = new moodle_url($CFG->wwwroot.'/question/contextmoveq.php',
463 array('returnurl' => $returnurl,
464 'ids'=>$questionidlist,
465 'tocatid'=> $tocategoryid));
466 if ($cm){
467 $movecontexturl->param('cmid', $cm->id);
468 } else {
469 $movecontexturl->param('courseid', $COURSE->id);
86909ce0 470 }
271e6dec 471 redirect($movecontexturl->out());
86909ce0 472 }
473 }
474 }
475
8e77884c 476 if (optional_param('deleteselected', false, PARAM_BOOL)) { // delete selected questions from the category
477 if (($confirm = optional_param('confirm', '', PARAM_ALPHANUM)) and confirm_sesskey()) { // teacher has already confirmed the action
86909ce0 478 $deleteselected = required_param('deleteselected');
8e77884c 479 if ($confirm == md5($deleteselected)) {
86909ce0 480 if ($questionlist = explode(',', $deleteselected)) {
481 // for each question either hide it if it is in use or delete it
482 foreach ($questionlist as $questionid) {
271e6dec 483 question_require_capability_on($questionid, 'edit');
f34488b2 484 if ($DB->record_exists('quiz_question_instances', array('question' => $questionid))) {
fec2094e 485 if (!$DB->set_field('question', 'hidden', 1, array('id' => $questionid))) {
271e6dec 486 question_require_capability_on($questionid, 'edit');
ac93d63d 487 print_error('cannothidequestion', 'question');
86909ce0 488 }
489 } else {
490 delete_question($questionid);
491 }
492 }
493 }
86909ce0 494 redirect($pageurl->out());
495 } else {
ac93d63d 496 print_error('invalidconfirm', 'question');
86909ce0 497 }
86909ce0 498 }
499 }
500
501 // Unhide a question
8e77884c 502 if(($unhide = optional_param('unhide', '', PARAM_INT)) and confirm_sesskey()) {
271e6dec 503 question_require_capability_on($unhide, 'edit');
f34488b2 504 if(!$DB->set_field('question', 'hidden', 0, array('id', $unhide))) {
ac93d63d 505 print_error('cannotunhidequestion', 'question');
86909ce0 506 }
507 redirect($pageurl->out());
508 }
271e6dec 509}
8e77884c 510
271e6dec 511/**
512 * Shows the question bank editing interface.
513 *
514 * The function also processes a number of actions:
515 *
516 * Actions affecting the question pool:
517 * move Moves a question to a different category
518 * deleteselected Deletes the selected questions from the category
519 * Other actions:
520 * category Chooses the category
521 * displayoptions Sets display options
522 *
271e6dec 523 * @param moodle_url $pageurl object representing this pages url.
524 */
525function question_showbank($tabname, $contexts, $pageurl, $cm, $page, $perpage, $sortorder, $sortorderdecoded, $cat, $recurse, $showhidden, $showquestiontext){
f34488b2 526 global $COURSE, $DB;
271e6dec 527
8e77884c 528 if (optional_param('deleteselected', false, PARAM_BOOL)){ // teacher still has to confirm
271e6dec 529 // make a list of all the questions that are selected
5412cd28 530 $rawquestions = $_REQUEST; // This code is called by both POST forms and GET links, so cannot use data_submitted.
271e6dec 531 $questionlist = ''; // comma separated list of ids of questions to be deleted
532 $questionnames = ''; // string with names of questions separated by <br /> with
533 // an asterix in front of those that are in use
534 $inuse = false; // set to true if at least one of the questions is in use
535 foreach ($rawquestions as $key => $value) { // Parse input for question ids
536 if (preg_match('!^q([0-9]+)$!', $key, $matches)) {
8e77884c 537 $key = $matches[1];
538 $questionlist .= $key.',';
271e6dec 539 question_require_capability_on($key, 'edit');
f34488b2 540 if ($DB->record_exists('quiz_question_instances', array('question' => $key))) {
271e6dec 541 $questionnames .= '* ';
542 $inuse = true;
543 }
f34488b2 544 $questionnames .= $DB->get_field('question', 'name', array('id' => $key)).'<br />';
271e6dec 545 }
546 }
547 if (!$questionlist) { // no questions were selected
548 redirect($pageurl->out());
549 }
550 $questionlist = rtrim($questionlist, ',');
551
552 // Add an explanation about questions in use
553 if ($inuse) {
554 $questionnames .= '<br />'.get_string('questionsinuse', 'quiz');
555 }
556 notice_yesno(get_string("deletequestionscheck", "quiz", $questionnames),
557 $pageurl->out_action(array('deleteselected'=>$questionlist, 'confirm'=>md5($questionlist))),
558 $pageurl->out_action());
559
560 echo '</td></tr>';
561 echo '</table>';
562 print_footer($COURSE);
563 exit;
564 }
565
86909ce0 566
86909ce0 567 // starts with category selection form
568 print_box_start('generalbox questionbank');
569 print_heading(get_string('questionbank', 'question'), '', 2);
271e6dec 570 question_category_form($contexts->having_one_edit_tab_cap($tabname), $pageurl, $cat, $recurse, $showhidden, $showquestiontext);
571
86909ce0 572 // continues with list of questions
271e6dec 573 question_list($contexts->having_one_edit_tab_cap($tabname), $pageurl, $cat, isset($cm) ? $cm : null,
574 $recurse, $page, $perpage, $showhidden, $sortorder, $sortorderdecoded, $showquestiontext,
575 $contexts->having_cap('moodle/question:add'));
86909ce0 576
577 print_box_end();
578}
b72ff476 579/**
580 * Common setup for all pages for editing questions.
271e6dec 581 * @param string $edittab code for this edit tab
b72ff476 582 * @param boolean $requirecmid require cmid? default false
583 * @param boolean $requirecourseid require courseid, if cmid is not given? default true
271e6dec 584 * @return array $thispageurl, $contexts, $cmid, $cm, $module, $pagevars
b72ff476 585 */
271e6dec 586function question_edit_setup($edittab, $requirecmid = false, $requirecourseid = true){
f34488b2 587 global $COURSE, $QUESTION_EDITTABCAPS, $DB;
271e6dec 588
589 //$thispageurl is used to construct urls for all question edit pages we link to from this page. It contains an array
36e298bc 590 //of parameters that are passed from page to page.
b72ff476 591 $thispageurl = new moodle_url();
592 if ($requirecmid){
593 $cmid =required_param('cmid', PARAM_INT);
594 } else {
595 $cmid = optional_param('cmid', 0, PARAM_INT);
596 }
597 if ($cmid){
271e6dec 598 list($module, $cm) = get_module_from_cmid($cmid);
b72ff476 599 $courseid = $cm->course;
600 $thispageurl->params(compact('cmid'));
271e6dec 601 require_login($courseid, false, $cm);
602 $thiscontext = get_context_instance(CONTEXT_MODULE, $cmid);
b72ff476 603 } else {
604 $module = null;
605 $cm = null;
606 if ($requirecourseid){
607 $courseid = required_param('courseid', PARAM_INT);
608 } else {
609 $courseid = optional_param('courseid', 0, PARAM_INT);
610 }
611 if ($courseid){
612 $thispageurl->params(compact('courseid'));
271e6dec 613 require_login($courseid, false);
614 $thiscontext = get_context_instance(CONTEXT_COURSE, $courseid);
615 } else {
616 $thiscontext = null;
b72ff476 617 }
618 }
271e6dec 619
620 if ($thiscontext){
621 $contexts = new question_edit_contexts($thiscontext);
622 $contexts->require_one_edit_tab_cap($edittab);
623
624 } else {
625 $contexts = null;
626 }
627
628
629
36e298bc 630 $pagevars['qpage'] = optional_param('qpage', -1, PARAM_INT);
271e6dec 631
7bc26c8f 632 //pass 'cat' from page to page and when 'category' comes from a drop down menu
271e6dec 633 //then we also reset the qpage so we go to page 1 of
7bc26c8f 634 //a new cat.
271e6dec 635 $pagevars['cat'] = optional_param('cat', 0, PARAM_SEQUENCE);// if empty will be set up later
636 if ($category = optional_param('category', 0, PARAM_SEQUENCE)){
a18fbcfb 637 if ($pagevars['cat'] != $category){ // is this a move to a new category?
638 $pagevars['cat'] = $category;
639 $pagevars['qpage'] = 0;
640 }
7bc26c8f 641 }
642 if ($pagevars['cat']){
643 $thispageurl->param('cat', $pagevars['cat']);
644 }
b72ff476 645 if ($pagevars['qpage'] > -1) {
646 $thispageurl->param('qpage', $pagevars['qpage']);
647 } else {
648 $pagevars['qpage'] = 0;
649 }
650
36e298bc 651 $pagevars['qperpage'] = optional_param('qperpage', -1, PARAM_INT);
b72ff476 652 if ($pagevars['qperpage'] > -1) {
653 $thispageurl->param('qperpage', $pagevars['qperpage']);
654 } else {
655 $pagevars['qperpage'] = DEFAULT_QUESTIONS_PER_PAGE;
656 }
271e6dec 657
36e298bc 658 $sortoptions = array('alpha' => 'name, qtype ASC',
659 'typealpha' => 'qtype, name ASC',
660 'age' => 'id ASC');
661
662 if ($sortorder = optional_param('qsortorder', '', PARAM_ALPHA)) {
663 $pagevars['qsortorderdecoded'] = $sortoptions[$sortorder];
664 $pagevars['qsortorder'] = $sortorder;
665 $thispageurl->param('qsortorder', $sortorder);
b72ff476 666 } else {
7bc26c8f 667 $pagevars['qsortorderdecoded'] = $sortoptions['typealpha'];
668 $pagevars['qsortorder'] = 'typealpha';
271e6dec 669 }
36e298bc 670
271e6dec 671 $defaultcategory = question_make_default_categories($contexts->all());
672
673 $contextlistarr = array();
674 foreach ($contexts->having_one_edit_tab_cap($edittab) as $context){
675 $contextlistarr[] = "'$context->id'";
676 }
677 $contextlist = join($contextlistarr, ' ,');
678 if (!empty($pagevars['cat'])){
679 $catparts = explode(',', $pagevars['cat']);
f34488b2 680 if (!$catparts[0] || (FALSE !== array_search($catparts[1], $contextlistarr)) ||
681 !$DB->count_records_select("question_categories", "id = ? AND contextid = ?", array($catparts[0], $catparts[1]))) {
5a2a5331 682 print_error('invalidcategory', 'quiz');
271e6dec 683 }
684 } else {
685 $category = $defaultcategory;
686 $pagevars['cat'] = "$category->id,$category->contextid";
36e298bc 687 }
688
689 if(($recurse = optional_param('recurse', -1, PARAM_BOOL)) != -1) {
690 $pagevars['recurse'] = $recurse;
691 $thispageurl->param('recurse', $recurse);
692 } else {
693 $pagevars['recurse'] = 1;
694 }
271e6dec 695
36e298bc 696 if(($showhidden = optional_param('showhidden', -1, PARAM_BOOL)) != -1) {
697 $pagevars['showhidden'] = $showhidden;
698 $thispageurl->param('showhidden', $showhidden);
699 } else {
700 $pagevars['showhidden'] = 0;
701 }
271e6dec 702
36e298bc 703 if(($showquestiontext = optional_param('showquestiontext', -1, PARAM_BOOL)) != -1) {
704 $pagevars['showquestiontext'] = $showquestiontext;
705 $thispageurl->param('showquestiontext', $showquestiontext);
706 } else {
707 $pagevars['showquestiontext'] = 0;
708 }
271e6dec 709
986effb6 710 //category list page
711 $pagevars['cpage'] = optional_param('cpage', 1, PARAM_INT);
712 if ($pagevars['cpage'] != 1){
713 $thispageurl->param('cpage', $pagevars['cpage']);
714 }
36e298bc 715
271e6dec 716
717 return array($thispageurl, $contexts, $cmid, $cm, $module, $pagevars);
718}
719class question_edit_contexts{
720 var $allcontexts;
721 /**
722 * @param current context
723 */
724 function question_edit_contexts($thiscontext){
725 $pcontextids = get_parent_contexts($thiscontext);
726 $contexts = array($thiscontext);
727 foreach ($pcontextids as $pcontextid){
728 $contexts[] = get_context_instance_by_id($pcontextid);
729 }
730 $this->allcontexts = $contexts;
731 }
732 /**
733 * @return array all parent contexts
734 */
735 function all(){
736 return $this->allcontexts;
737 }
738 /**
739 * @return object lowest context which must be either the module or course context
740 */
741 function lowest(){
742 return $this->allcontexts[0];
743 }
744 /**
745 * @param string $cap capability
746 * @return array parent contexts having capability, zero based index
747 */
748 function having_cap($cap){
749 $contextswithcap = array();
750 foreach ($this->allcontexts as $context){
751 if (has_capability($cap, $context)){
752 $contextswithcap[] = $context;
753 }
754 }
755 return $contextswithcap;
756 }
757 /**
758 * @param array $caps capabilities
759 * @return array parent contexts having at least one of $caps, zero based index
760 */
761 function having_one_cap($caps){
762 $contextswithacap = array();
763 foreach ($this->allcontexts as $context){
764 foreach ($caps as $cap){
765 if (has_capability($cap, $context)){
766 $contextswithacap[] = $context;
767 break; //done with caps loop
768 }
769 }
770 }
771 return $contextswithacap;
772 }
773 /**
774 * @param string $tabname edit tab name
775 * @return array parent contexts having at least one of $caps, zero based index
776 */
777 function having_one_edit_tab_cap($tabname){
778 global $QUESTION_EDITTABCAPS;
779 return $this->having_one_cap($QUESTION_EDITTABCAPS[$tabname]);
780 }
781 /**
782 * Has at least one parent context got the cap $cap?
783 *
784 * @param string $cap capability
785 * @return boolean
786 */
787 function have_cap($cap){
788 return (count($this->having_cap($cap)));
789 }
790
791 /**
792 * Has at least one parent context got one of the caps $caps?
793 *
794 * @param string $cap capability
795 * @return boolean
796 */
797 function have_one_cap($caps){
798 foreach ($caps as $cap){
799 if ($this->have_cap($cap)){
800 return true;
801 }
802 }
803 return false;
804 }
805 /**
806 * Has at least one parent context got one of the caps for actions on $tabname
807 *
808 * @param string $tabname edit tab name
809 * @return boolean
810 */
811 function have_one_edit_tab_cap($tabname){
812 global $QUESTION_EDITTABCAPS;
813 return $this->have_one_cap($QUESTION_EDITTABCAPS[$tabname]);
814 }
815 /**
816 * Throw error if at least one parent context hasn't got the cap $cap
817 *
818 * @param string $cap capability
819 */
820 function require_cap($cap){
821 if (!$this->have_cap($cap)){
822 print_error('nopermissions', '', '', $cap);
823 }
824 }
825 /**
826 * Throw error if at least one parent context hasn't got one of the caps $caps
827 *
828 * @param array $cap capabilities
829 */
830 function require_one_cap($caps){
831 if (!$this->have_one_cap($caps)){
832 $capsstring = join($caps, ', ');
833 print_error('nopermissions', '', '', $capsstring);
834 }
835 }
836 /**
837 * Throw error if at least one parent context hasn't got one of the caps $caps
838 *
839 * @param string $tabname edit tab name
840 */
841 function require_one_edit_tab_cap($tabname){
842 if (!$this->have_one_edit_tab_cap($tabname)){
843 print_error('nopermissions', '', '', 'access question edit tab '.$tabname);
844 }
845 }
846}
847
848//capabilities for each page of edit tab.
849//this determines which contexts' categories are available. At least one
850//page is displayed if user has one of the capability on at least one context
851$QUESTION_EDITTABCAPS = array(
a856c14e 852 'editq' => array('moodle/question:add',
853 'moodle/question:editmine',
854 'moodle/question:editall',
855 'moodle/question:viewmine',
856 'moodle/question:viewall',
857 'moodle/question:usemine',
858 'moodle/question:useall',
859 'moodle/question:movemine',
860 'moodle/question:moveall'),
861 'questions'=>array('moodle/question:add',
862 'moodle/question:editmine',
863 'moodle/question:editall',
864 'moodle/question:viewmine',
865 'moodle/question:viewall',
866 'moodle/question:movemine',
867 'moodle/question:moveall'),
868 'categories'=>array('moodle/question:managecategory'),
869 'import'=>array('moodle/question:add'),
870 'export'=>array('moodle/question:viewall', 'moodle/question:viewmine'));
271e6dec 871
872/**
873 * Make sure user is logged in as required in this context.
874 */
875function require_login_in_context($contextorid = null){
f34488b2 876 global $DB;
271e6dec 877 if (!is_object($contextorid)){
878 $context = get_context_instance_by_id($contextorid);
879 } else {
880 $context = $contextorid;
881 }
882 if ($context && ($context->contextlevel == CONTEXT_COURSE)) {
883 require_login($context->instanceid);
884 } else if ($context && ($context->contextlevel == CONTEXT_MODULE)) {
f34488b2 885 if ($cm = $DB->get_record('course_modules',array('id' =>$context->instanceid))) {
886 if (!$course = $DB->get_record('course', array('id' => $cm->course))) {
0be2c858 887 print_error('invalidcourseid');
271e6dec 888 }
889 require_course_login($course, true, $cm);
890
891 } else {
0be2c858 892 print_error('invalidcoursemodule');
271e6dec 893 }
894 } else if ($context && ($context->contextlevel == CONTEXT_SYSTEM)) {
895 if (!empty($CFG->forcelogin)) {
896 require_login();
897 }
898
899 } else {
900 require_login();
901 }
b72ff476 902}
871ab9a3 903?>