Merge branch 'w11_MDL-26634_19_ldapset' of git://github.com/skodak/moodle into MOODLE...
[moodle.git] / question / editlib.php
blobc18daf90849afdb45f8fe0c6dcec526552d97da9
1 <?php // $Id$
2 /**
3 * Functions used to show question editing interface
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
13 require_once($CFG->libdir.'/questionlib.php');
15 define('DEFAULT_QUESTIONS_PER_PAGE', 20);
17 function get_module_from_cmid($cmid){
18 global $CFG;
19 if (!$cmrec = get_record_sql("SELECT cm.*, md.name as modname
20 FROM {$CFG->prefix}course_modules cm,
21 {$CFG->prefix}modules md
22 WHERE cm.id = '$cmid' AND
23 md.id = cm.module")){
24 error('cmunknown');
25 } elseif (!$modrec =get_record($cmrec->modname, 'id', $cmrec->instance)) {
26 error('cmunknown');
28 $modrec->instance = $modrec->id;
29 $modrec->cmid = $cmrec->id;
30 $cmrec->name = $modrec->name;
32 return array($modrec, $cmrec);
34 /**
35 * Function to read all questions for category into big array
37 * @param int $category category number
38 * @param bool $noparent if true only questions with NO parent will be selected
39 * @param bool $recurse include subdirectories
40 * @param bool $export set true if this is called by questionbank export
41 * @author added by Howard Miller June 2004
43 function get_questions_category( $category, $noparent=false, $recurse=true, $export=true ) {
45 global $QTYPES;
47 // questions will be added to an array
48 $qresults = array();
50 // build sql bit for $noparent
51 $npsql = '';
52 if ($noparent) {
53 $npsql = " and parent='0' ";
56 // get (list) of categories
57 if ($recurse) {
58 $categorylist = question_categorylist( $category->id );
60 else {
61 $categorylist = $category->id;
64 // get the list of questions for the category
65 if ($questions = get_records_select("question","category IN ($categorylist) $npsql", "qtype, name ASC")) {
67 // iterate through questions, getting stuff we need
68 foreach($questions as $question) {
69 $questiontype = $QTYPES[$question->qtype];
70 $question->export_process = $export;
71 $questiontype->get_question_options( $question );
72 $qresults[] = $question;
76 return $qresults;
79 /**
80 * @param integer $categoryid a category id.
81 * @return boolean whether this is the only top-level category in a context.
83 function question_is_only_toplevel_category_in_context($categoryid) {
84 global $CFG;
85 return 1 == count_records_sql("
86 SELECT count(*)
87 FROM {$CFG->prefix}question_categories c1,
88 {$CFG->prefix}question_categories c2
89 WHERE c2.id = $categoryid
90 AND c1.contextid = c2.contextid
91 AND c1.parent = 0 AND c2.parent = 0");
94 /**
95 * Check whether this user is allowed to delete this category.
97 * @param integer $todelete a category id.
99 function question_can_delete_cat($todelete) {
100 if (question_is_only_toplevel_category_in_context($todelete)) {
101 error('You can\'t delete that category it is the default category for this context.');
102 } else {
103 $contextid = get_field('question_categories', 'contextid', 'id', $todelete);
104 require_capability('moodle/question:managecategory', get_context_instance_by_id($contextid));
108 * prints a form to choose categories
110 function question_category_form($contexts, $pageurl, $current, $recurse=1, $showhidden=false, $showquestiontext=false) {
111 global $CFG;
114 /// Get all the existing categories now
115 $catmenu = question_category_options($contexts, false, 0, true);
117 $strcategory = get_string('category', 'quiz');
118 $strshow = get_string('show', 'quiz');
119 $streditcats = get_string('editcategories', 'quiz');
121 popup_form ('edit.php?'.$pageurl->get_query_string().'&amp;category=', $catmenu, 'catmenu', $current, '', '', '', false, 'self', "<strong>$strcategory</strong>");
123 echo '<form method="get" action="edit.php" id="displayoptions">';
124 echo "<fieldset class='invisiblefieldset'>";
125 echo $pageurl->hidden_params_out(array('recurse', 'showhidden', 'showquestiontext'));
126 question_category_form_checkbox('recurse', $recurse);
127 question_category_form_checkbox('showhidden', $showhidden);
128 question_category_form_checkbox('showquestiontext', $showquestiontext);
129 echo '<noscript><div class="centerpara"><input type="submit" value="'. get_string('go') .'" />';
130 echo '</div></noscript></fieldset></form>';
134 * Private funciton to help the preceeding function.
136 function question_category_form_checkbox($name, $checked) {
137 echo '<div><input type="hidden" id="' . $name . '_off" name="' . $name . '" value="0" />';
138 echo '<input type="checkbox" id="' . $name . '_on" name="' . $name . '" value="1"';
139 if ($checked) {
140 echo ' checked="checked"';
142 echo ' onchange="getElementById(\'displayoptions\').submit(); return true;" />';
143 echo '<label for="' . $name . '_on">';
144 print_string($name, 'quiz');
145 echo "</label></div>\n";
149 * Prints the table of questions in a category with interactions
151 * @param object $course The course object
152 * @param int $categoryid The id of the question category to be displayed
153 * @param int $cm The course module record if we are in the context of a particular module, 0 otherwise
154 * @param int $recurse This is 1 if subcategories should be included, 0 otherwise
155 * @param int $page The number of the page to be displayed
156 * @param int $perpage Number of questions to show per page
157 * @param boolean $showhidden True if also hidden questions should be displayed
158 * @param boolean $showquestiontext whether the text of each question should be shown in the list
160 function question_list($contexts, $pageurl, $categoryandcontext, $cm = null,
161 $recurse=1, $page=0, $perpage=100, $showhidden=false, $sortorder='typename', $sortorderdecoded='qtype, name ASC',
162 $showquestiontext = false, $addcontexts = array()) {
163 global $USER, $CFG, $THEME, $COURSE;
165 $lastchangedid=optional_param('lastchanged',0,PARAM_INT);
166 list($categoryid, $contextid)= explode(',', $categoryandcontext);
168 $qtypemenu = question_type_menu();
170 $strcategory = get_string("category", "quiz");
171 $strquestion = get_string("question", "quiz");
172 $straddquestions = get_string("addquestions", "quiz");
173 $strimportquestions = get_string("importquestions", "quiz");
174 $strexportquestions = get_string("exportquestions", "quiz");
175 $strnoquestions = get_string("noquestions", "quiz");
176 $strselect = get_string("select", "quiz");
177 $strselectall = get_string("selectall", "quiz");
178 $strselectnone = get_string("selectnone", "quiz");
179 $strcreatenewquestion = get_string("createnewquestion", "quiz");
180 $strquestionname = get_string("questionname", "quiz");
181 $strdelete = get_string("delete");
182 $stredit = get_string("edit");
183 $strmove = get_string('moveqtoanothercontext', 'question');
184 $strview = get_string("view");
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");
192 if (!$categoryid) {
193 echo "<p style=\"text-align:center;\"><b>";
194 print_string("selectcategoryabove", "quiz");
195 echo "</b></p>";
196 return;
199 if (!$category = get_record('question_categories', 'id', $categoryid, 'contextid', $contextid)) {
200 notify('Category not found!');
201 return;
203 $catcontext = get_context_instance_by_id($contextid);
204 $canadd = has_capability('moodle/question:add', $catcontext);
205 //check for capabilities on all questions in category, will also apply to sub cats.
206 $caneditall =has_capability('moodle/question:editall', $catcontext);
207 $canuseall =has_capability('moodle/question:useall', $catcontext);
208 $canmoveall =has_capability('moodle/question:moveall', $catcontext);
210 if ($cm AND $cm->modname == 'quiz') {
211 $quizid = $cm->instance;
212 } else {
213 $quizid = 0;
215 $returnurl = $pageurl->out();
216 $questionurl = new moodle_url("$CFG->wwwroot/question/question.php",
217 array('returnurl' => $returnurl));
218 if ($cm!==null){
219 $questionurl->param('cmid', $cm->id);
220 } else {
221 $questionurl->param('courseid', $COURSE->id);
223 $questionmoveurl = new moodle_url("$CFG->wwwroot/question/contextmoveq.php",
224 array('returnurl' => $returnurl));
225 if ($cm!==null){
226 $questionmoveurl->param('cmid', $cm->id);
227 } else {
228 $questionmoveurl->param('courseid', $COURSE->id);
230 echo '<div class="boxaligncenter">';
231 $formatoptions = new stdClass;
232 $formatoptions->noclean = true;
233 echo format_text($category->info, FORMAT_MOODLE, $formatoptions, $COURSE->id);
235 echo '<table><tr>';
237 if ($canadd) {
238 echo '<td valign="top" align="right">';
239 popup_form ($questionurl->out(false, array('category' => $category->id)).'&amp;qtype=', $qtypemenu, "addquestion", "", "choose", "", "", false, "self", "<strong>$strcreatenewquestion</strong>");
240 echo '</td><td valign="top" align="right">';
241 helpbutton("questiontypes", $strcreatenewquestion, "quiz");
242 echo '</td>';
244 else {
245 echo '<td>';
246 print_string('nopermissionadd', 'question');
247 echo '</td>';
250 echo '</tr></table>';
251 echo '</div>';
253 $categorylist = ($recurse) ? question_categorylist($category->id) : $category->id;
255 // hide-feature
256 $showhidden = $showhidden ? '' : " AND hidden = '0'";
258 if (!$totalnumber = count_records_select('question', "category IN ($categorylist) AND parent = '0' $showhidden")) {
259 echo "<p style=\"text-align:center;\">";
260 print_string("noquestions", "quiz");
261 echo "</p>";
262 return;
265 if (!$questions = get_records_select('question', "category IN ($categorylist) AND parent = '0' $showhidden", $sortorderdecoded, '*', $page*$perpage, $perpage)) {
266 // There are no questions on the requested page.
267 $page = 0;
268 if (!$questions = get_records_select('question', "category IN ($categorylist) AND parent = '0' $showhidden", $sortorderdecoded, '*', 0, $perpage)) {
269 // There are no questions at all
270 echo "<p style=\"text-align:center;\">";
271 print_string("noquestions", "quiz");
272 echo "</p>";
273 return;
277 print_paging_bar($totalnumber, $page, $perpage, $pageurl, 'qpage');
279 echo question_sort_options($pageurl, $sortorder);
282 echo '<form method="post" action="edit.php">';
283 echo '<fieldset class="invisiblefieldset" style="display: block;">';
284 echo '<input type="hidden" name="sesskey" value="'.$USER->sesskey.'" />';
285 echo $pageurl->hidden_params_out();
286 echo '<table id="categoryquestions" style="width: 100%"><tr>';
287 echo "<th style=\"white-space:nowrap;\" class=\"header\" scope=\"col\">$straction</th>";
289 echo "<th style=\"white-space:nowrap; text-align: left;\" class=\"header\" scope=\"col\">$strquestionname</th>
290 <th style=\"white-space:nowrap; text-align: right;\" class=\"header\" scope=\"col\">$strtype</th>";
291 echo "</tr>\n";
292 foreach ($questions as $question) {
293 $nameclass = '';
294 $textclass = '';
295 if ($question->hidden) {
296 $nameclass = 'dimmed_text';
297 $textclass = 'dimmed_text';
299 if ($showquestiontext) {
300 $nameclass .= ' header';
302 if ($question->id==$lastchangedid) {
303 $nameclass='highlight';
305 if ($nameclass) {
306 $nameclass = 'class="' . $nameclass . '"';
308 if ($textclass) {
309 $textclass = 'class="' . $textclass . '"';
312 echo "<tr>\n<td style=\"white-space:nowrap;\" $nameclass>\n";
314 $canuseq = question_has_capability_on($question, 'use', $question->category);
315 if (function_exists('module_specific_actions')) {
316 echo module_specific_actions($pageurl, $question->id, $cm->id, $canuseq);
319 // preview
320 if ($canuseq) {
321 $quizorcourseid = $quizid?('&amp;quizid=' . $quizid):('&amp;courseid=' .$COURSE->id);
322 link_to_popup_window('/question/preview.php?id=' . $question->id . $quizorcourseid, 'questionpreview',
323 "<img src=\"$CFG->pixpath/t/preview.gif\" class=\"iconsmall\" alt=\"$strpreview\" />",
324 0, 0, $strpreview, QUESTION_PREVIEW_POPUP_OPTIONS);
326 // edit, hide, delete question, using question capabilities, not quiz capabilieies
327 if (question_has_capability_on($question, 'edit', $question->category) || question_has_capability_on($question, 'move', $question->category)) {
328 echo "<a title=\"$stredit\" href=\"".$questionurl->out(false, array('id'=>$question->id))."\"><img
329 src=\"$CFG->pixpath/t/edit.gif\" alt=\"$stredit\" /></a>&nbsp;";
330 } elseif (question_has_capability_on($question, 'view', $question->category)){
331 echo "<a title=\"$strview\" href=\"".$questionurl->out(false, array('id'=>$question->id))."\"><img
332 src=\"$CFG->pixpath/i/info.gif\" alt=\"$strview\" /></a>&nbsp;";
335 if (question_has_capability_on($question, 'move', $question->category) && question_has_capability_on($question, 'view', $question->category)) {
336 echo "<a title=\"$strmove\" href=\"".$questionurl->out(false, array('id'=>$question->id, 'movecontext'=>1))."\"><img
337 src=\"$CFG->pixpath/t/move.gif\" alt=\"$strmove\" /></a>&nbsp;";
340 if (question_has_capability_on($question, 'edit', $question->category)) {
341 // hide-feature
342 if($question->hidden) {
343 echo "<a title=\"$strrestore\" href=\"edit.php?".$pageurl->get_query_string()."&amp;unhide=$question->id&amp;sesskey=$USER->sesskey\"><img
344 src=\"$CFG->pixpath/t/restore.gif\" alt=\"$strrestore\" /></a>";
345 } else {
346 echo "<a title=\"$strdelete\" href=\"edit.php?".$pageurl->get_query_string()."&amp;deleteselected=$question->id&amp;q$question->id=1\"><img
347 src=\"$CFG->pixpath/t/delete.gif\" alt=\"$strdelete\" /></a>";
350 if ($caneditall || $canmoveall || $canuseall){
351 echo "&nbsp;<input title=\"$strselect\" type=\"checkbox\" name=\"q$question->id\" value=\"1\" />";
353 echo "</td>\n";
355 echo "<td $nameclass>" . format_string($question->name) . "</td>\n";
356 echo "<td $nameclass style='text-align: right'>\n";
357 print_question_icon($question);
358 echo "</td>\n";
359 echo "</tr>\n";
360 if($showquestiontext){
361 echo '<tr><td colspan="3" ' . $textclass . '>';
362 $formatoptions = new stdClass;
363 $formatoptions->noclean = true;
364 $formatoptions->para = false;
365 echo format_text($question->questiontext, $question->questiontextformat,
366 $formatoptions, $COURSE->id);
367 echo "</td></tr>\n";
370 echo "</table>\n";
372 $paging = print_paging_bar($totalnumber, $page, $perpage, $pageurl, 'qpage', false, true);
373 if ($totalnumber > DEFAULT_QUESTIONS_PER_PAGE) {
374 if ($perpage == DEFAULT_QUESTIONS_PER_PAGE) {
375 $showall = '<a href="edit.php?'.$pageurl->get_query_string(array('qperpage'=>1000)).'">'.get_string('showall', 'moodle', $totalnumber).'</a>';
376 } else {
377 $showall = '<a href="edit.php?'.$pageurl->get_query_string(array('qperpage'=>DEFAULT_QUESTIONS_PER_PAGE)).'">'.get_string('showperpage', 'moodle', DEFAULT_QUESTIONS_PER_PAGE).'</a>';
379 if ($paging) {
380 $paging = substr($paging, 0, strrpos($paging, '</div>'));
381 $paging .= "<br />$showall</div>";
382 } else {
383 $paging = "<div class='paging'>$showall</div>";
386 echo $paging;
388 if ($caneditall || $canmoveall || $canuseall){
389 echo '<a href="javascript:select_all_in(\'TABLE\',null,\'categoryquestions\');">'.$strselectall.'</a> /'.
390 ' <a href="javascript:deselect_all_in(\'TABLE\',null,\'categoryquestions\');">'.$strselectnone.'</a>';
391 echo '<br />';
392 echo '<strong>&nbsp;'.get_string('withselected', 'quiz').':</strong><br />';
394 if (function_exists('module_specific_buttons')) {
395 echo module_specific_buttons($cm->id);
397 // print delete and move selected question
398 if ($caneditall) {
399 echo '<input type="submit" name="deleteselected" value="'.$strdelete."\" />\n";
401 if ($canmoveall && count($addcontexts)) {
402 echo '<input type="submit" name="move" value="'.get_string('moveto', 'quiz')."\" />\n";
403 question_category_select_menu($addcontexts, false, 0, "$category->id,$category->contextid");
406 if (function_exists('module_specific_controls') && $canuseall) {
407 echo module_specific_controls($totalnumber, $recurse, $category, $cm->id);
410 echo '</fieldset>';
411 echo "</form>\n";
413 function question_sort_options($pageurl, $sortorder){
414 global $USER;
415 //sort options
416 $html = "<div class=\"mdl-align\">";
417 $html .= '<form method="post" action="edit.php">';
418 $html .= '<fieldset class="invisiblefieldset" style="display: block;">';
419 $html .= '<input type="hidden" name="sesskey" value="'.$USER->sesskey.'" />';
420 $html .= $pageurl->hidden_params_out(array('qsortorder'));
421 $sortoptions = array('alpha' => get_string("sortalpha", "quiz"),
422 'typealpha' => get_string("sorttypealpha", "quiz"),
423 'age' => get_string("sortage", "quiz"));
424 $html .= choose_from_menu ($sortoptions, 'qsortorder', $sortorder, false, 'this.form.submit();', '0', true);
425 $html .= '<noscript><div><input type="submit" value="'.get_string("sortsubmit", "quiz").'" /></div></noscript>';
426 $html .= '</fieldset>';
427 $html .= "</form>\n";
428 $html .= "</div>\n";
429 return $html;
432 function question_showbank_actions($pageurl, $cm){
433 global $CFG, $COURSE;
434 /// Now, check for commands on this page and modify variables as necessary
435 if (optional_param('move', false, PARAM_BOOL) and confirm_sesskey()) { /// Move selected questions to new category
436 $category = required_param('category', PARAM_SEQUENCE);
437 list($tocategoryid, $contextid) = explode(',', $category);
438 if (! $tocategory = get_record('question_categories', 'id', $tocategoryid, 'contextid', $contextid)) {
439 error('Could not find category record');
441 $tocontext = get_context_instance_by_id($contextid);
442 require_capability('moodle/question:add', $tocontext);
443 $rawdata = (array) data_submitted();
444 $questionids = array();
445 foreach ($rawdata as $key => $value) { // Parse input for question ids
446 if (preg_match('!^q([0-9]+)$!', $key, $matches)) {
447 $key = $matches[1];
448 $questionids[] = $key;
451 if ($questionids){
452 $questionidlist = join($questionids, ',');
453 $sql = "SELECT q.*, c.contextid FROM {$CFG->prefix}question q, {$CFG->prefix}question_categories c WHERE q.id IN ($questionidlist) AND c.id = q.category";
454 if (!$questions = get_records_sql($sql)){
455 print_error('questiondoesnotexist', 'question', $pageurl->out());
457 $checkforfiles = false;
458 foreach ($questions as $question){
459 //check capabilities
460 question_require_capability_on($question, 'move');
461 $fromcontext = get_context_instance_by_id($question->contextid);
462 if (get_filesdir_from_context($fromcontext) != get_filesdir_from_context($tocontext)){
463 $checkforfiles = true;
466 $returnurl = $pageurl->out(false, array('category'=>"$tocategoryid,$contextid"));
467 if (!$checkforfiles){
468 if (!question_move_questions_to_category(implode(',', $questionids), $tocategory->id)) {
469 print_error('errormovingquestions', 'question', $returnurl, $questionids);
471 redirect($returnurl);
472 } else {
473 $movecontexturl = new moodle_url($CFG->wwwroot.'/question/contextmoveq.php',
474 array('returnurl' => $returnurl,
475 'ids'=>$questionidlist,
476 'tocatid'=> $tocategoryid));
477 if ($cm){
478 $movecontexturl->param('cmid', $cm->id);
479 } else {
480 $movecontexturl->param('courseid', $COURSE->id);
482 redirect($movecontexturl->out());
487 if (optional_param('deleteselected', false, PARAM_BOOL)) { // delete selected questions from the category
488 if (($confirm = optional_param('confirm', '', PARAM_ALPHANUM)) and confirm_sesskey()) { // teacher has already confirmed the action
489 $deleteselected = required_param('deleteselected');
490 if ($confirm == md5($deleteselected)) {
491 if ($questionlist = explode(',', $deleteselected)) {
492 // for each question either hide it if it is in use or delete it
493 foreach ($questionlist as $questionid) {
494 question_require_capability_on($questionid, 'edit');
495 if (record_exists('quiz_question_instances', 'question', $questionid)) {
496 if (!set_field('question', 'hidden', 1, 'id', $questionid)) {
497 question_require_capability_on($questionid, 'edit');
498 error('Was not able to hide question');
500 } else {
501 delete_question($questionid);
505 redirect($pageurl->out());
506 } else {
507 error("Confirmation string was incorrect");
512 // Unhide a question
513 if(($unhide = optional_param('unhide', '', PARAM_INT)) and confirm_sesskey()) {
514 question_require_capability_on($unhide, 'edit');
515 if(!set_field('question', 'hidden', 0, 'id', $unhide)) {
516 error("Failed to unhide the question.");
518 redirect($pageurl->out());
523 * Shows the question bank editing interface.
525 * The function also processes a number of actions:
527 * Actions affecting the question pool:
528 * move Moves a question to a different category
529 * deleteselected Deletes the selected questions from the category
530 * Other actions:
531 * category Chooses the category
532 * displayoptions Sets display options
534 * @author Martin Dougiamas and many others. This has recently been extensively
535 * rewritten by Gustav Delius and other members of the Serving Mathematics project
536 * {@link http://maths.york.ac.uk/serving_maths}
537 * @param moodle_url $pageurl object representing this pages url.
539 function question_showbank($tabname, $contexts, $pageurl, $cm, $page, $perpage, $sortorder, $sortorderdecoded, $cat, $recurse, $showhidden, $showquestiontext){
540 global $COURSE;
542 if (optional_param('deleteselected', false, PARAM_BOOL)){ // teacher still has to confirm
543 // make a list of all the questions that are selected
544 $rawquestions = $_REQUEST; // This code is called by both POST forms and GET links, so cannot use data_submitted.
545 $questionlist = ''; // comma separated list of ids of questions to be deleted
546 $questionnames = ''; // string with names of questions separated by <br /> with
547 // an asterix in front of those that are in use
548 $inuse = false; // set to true if at least one of the questions is in use
549 foreach ($rawquestions as $key => $value) { // Parse input for question ids
550 if (preg_match('!^q([0-9]+)$!', $key, $matches)) {
551 $key = $matches[1];
552 $questionlist .= $key.',';
553 question_require_capability_on($key, 'edit');
554 if (record_exists('quiz_question_instances', 'question', $key)) {
555 $questionnames .= '* ';
556 $inuse = true;
558 $questionnames .= get_field('question', 'name', 'id', $key).'<br />';
561 if (!$questionlist) { // no questions were selected
562 redirect($pageurl->out());
564 $questionlist = rtrim($questionlist, ',');
566 // Add an explanation about questions in use
567 if ($inuse) {
568 $questionnames .= '<br />'.get_string('questionsinuse', 'quiz');
570 notice_yesno(get_string("deletequestionscheck", "quiz", $questionnames),
571 $pageurl->out_action(),
572 $pageurl->out(true),
573 array('deleteselected'=>$questionlist, 'confirm'=>md5($questionlist)),
574 $pageurl->params(), 'post', 'get');
576 echo '</td></tr>';
577 echo '</table>';
578 print_footer($COURSE);
579 exit;
583 // starts with category selection form
584 print_box_start('generalbox questionbank');
585 print_heading(get_string('questionbank', 'question'), '', 2);
586 question_category_form($contexts->having_one_edit_tab_cap($tabname), $pageurl, $cat, $recurse, $showhidden, $showquestiontext);
588 // continues with list of questions
589 question_list($contexts->having_one_edit_tab_cap($tabname), $pageurl, $cat, isset($cm) ? $cm : null,
590 $recurse, $page, $perpage, $showhidden, $sortorder, $sortorderdecoded, $showquestiontext,
591 $contexts->having_cap('moodle/question:add'));
593 print_box_end();
596 * Common setup for all pages for editing questions.
597 * @param string $edittab code for this edit tab
598 * @param boolean $requirecmid require cmid? default false
599 * @param boolean $requirecourseid require courseid, if cmid is not given? default true
600 * @return array $thispageurl, $contexts, $cmid, $cm, $module, $pagevars
602 function question_edit_setup($edittab, $requirecmid = false, $requirecourseid = true){
603 global $COURSE, $QUESTION_EDITTABCAPS;
605 //$thispageurl is used to construct urls for all question edit pages we link to from this page. It contains an array
606 //of parameters that are passed from page to page.
607 $thispageurl = new moodle_url();
608 if ($requirecmid){
609 $cmid =required_param('cmid', PARAM_INT);
610 } else {
611 $cmid = optional_param('cmid', 0, PARAM_INT);
613 if ($cmid){
614 list($module, $cm) = get_module_from_cmid($cmid);
615 $courseid = $cm->course;
616 $thispageurl->params(compact('cmid'));
617 require_login($courseid, false, $cm);
618 $thiscontext = get_context_instance(CONTEXT_MODULE, $cmid);
619 } else {
620 $module = null;
621 $cm = null;
622 if ($requirecourseid){
623 $courseid = required_param('courseid', PARAM_INT);
624 } else {
625 $courseid = optional_param('courseid', 0, PARAM_INT);
627 if ($courseid){
628 $thispageurl->params(compact('courseid'));
629 require_login($courseid, false);
630 $thiscontext = get_context_instance(CONTEXT_COURSE, $courseid);
631 } else {
632 $thiscontext = null;
636 if ($thiscontext){
637 $contexts = new question_edit_contexts($thiscontext);
638 $contexts->require_one_edit_tab_cap($edittab);
640 } else {
641 $contexts = null;
646 $pagevars['qpage'] = optional_param('qpage', -1, PARAM_INT);
648 //pass 'cat' from page to page and when 'category' comes from a drop down menu
649 //then we also reset the qpage so we go to page 1 of
650 //a new cat.
651 $pagevars['cat'] = optional_param('cat', 0, PARAM_SEQUENCE);// if empty will be set up later
652 if ($category = optional_param('category', 0, PARAM_SEQUENCE)){
653 if ($pagevars['cat'] != $category){ // is this a move to a new category?
654 $pagevars['cat'] = $category;
655 $pagevars['qpage'] = 0;
658 if ($pagevars['cat']){
659 $thispageurl->param('cat', $pagevars['cat']);
661 if ($pagevars['qpage'] > -1) {
662 $thispageurl->param('qpage', $pagevars['qpage']);
663 } else {
664 $pagevars['qpage'] = 0;
667 $pagevars['qperpage'] = optional_param('qperpage', -1, PARAM_INT);
668 if ($pagevars['qperpage'] > -1) {
669 $thispageurl->param('qperpage', $pagevars['qperpage']);
670 } else {
671 $pagevars['qperpage'] = DEFAULT_QUESTIONS_PER_PAGE;
674 $sortoptions = array('alpha' => 'name, qtype ASC',
675 'typealpha' => 'qtype, name ASC',
676 'age' => 'id ASC');
678 if ($sortorder = optional_param('qsortorder', '', PARAM_ALPHA)) {
679 $pagevars['qsortorderdecoded'] = $sortoptions[$sortorder];
680 $pagevars['qsortorder'] = $sortorder;
681 $thispageurl->param('qsortorder', $sortorder);
682 } else {
683 $pagevars['qsortorderdecoded'] = $sortoptions['typealpha'];
684 $pagevars['qsortorder'] = 'typealpha';
687 $defaultcategory = question_make_default_categories($contexts->all());
689 $contextlistarr = array();
690 foreach ($contexts->having_one_edit_tab_cap($edittab) as $context){
691 $contextlistarr[] = "'$context->id'";
693 $contextlist = join($contextlistarr, ' ,');
694 if (!empty($pagevars['cat'])){
695 $catparts = explode(',', $pagevars['cat']);
696 if (!$catparts[0] || (FALSE !== array_search($catparts[1], $contextlistarr)) || !count_records_select("question_categories", "id = '".$catparts[0]."' AND contextid = $catparts[1]")) {
697 print_error('invalidcategory', 'quiz');
699 } else {
700 $category = $defaultcategory;
701 $pagevars['cat'] = "$category->id,$category->contextid";
704 if(($recurse = optional_param('recurse', -1, PARAM_BOOL)) != -1) {
705 $pagevars['recurse'] = $recurse;
706 $thispageurl->param('recurse', $recurse);
707 } else {
708 $pagevars['recurse'] = 1;
711 if(($showhidden = optional_param('showhidden', -1, PARAM_BOOL)) != -1) {
712 $pagevars['showhidden'] = $showhidden;
713 $thispageurl->param('showhidden', $showhidden);
714 } else {
715 $pagevars['showhidden'] = 0;
718 if(($showquestiontext = optional_param('showquestiontext', -1, PARAM_BOOL)) != -1) {
719 $pagevars['showquestiontext'] = $showquestiontext;
720 $thispageurl->param('showquestiontext', $showquestiontext);
721 } else {
722 $pagevars['showquestiontext'] = 0;
725 //category list page
726 $pagevars['cpage'] = optional_param('cpage', 1, PARAM_INT);
727 if ($pagevars['cpage'] < 1) {
728 $pagevars['cpage'] = 1;
730 if ($pagevars['cpage'] != 1){
731 $thispageurl->param('cpage', $pagevars['cpage']);
735 return array($thispageurl, $contexts, $cmid, $cm, $module, $pagevars);
737 class question_edit_contexts{
738 var $allcontexts;
740 * @param current context
742 function question_edit_contexts($thiscontext){
743 $pcontextids = get_parent_contexts($thiscontext);
744 $contexts = array($thiscontext);
745 foreach ($pcontextids as $pcontextid){
746 $contexts[] = get_context_instance_by_id($pcontextid);
748 $this->allcontexts = $contexts;
751 * @return array all parent contexts
753 function all(){
754 return $this->allcontexts;
757 * @return object lowest context which must be either the module or course context
759 function lowest(){
760 return $this->allcontexts[0];
763 * @param string $cap capability
764 * @return array parent contexts having capability, zero based index
766 function having_cap($cap){
767 $contextswithcap = array();
768 foreach ($this->allcontexts as $context){
769 if (has_capability($cap, $context)){
770 $contextswithcap[] = $context;
773 return $contextswithcap;
776 * @param array $caps capabilities
777 * @return array parent contexts having at least one of $caps, zero based index
779 function having_one_cap($caps){
780 $contextswithacap = array();
781 foreach ($this->allcontexts as $context){
782 foreach ($caps as $cap){
783 if (has_capability($cap, $context)){
784 $contextswithacap[] = $context;
785 break; //done with caps loop
789 return $contextswithacap;
792 * @param string $tabname edit tab name
793 * @return array parent contexts having at least one of $caps, zero based index
795 function having_one_edit_tab_cap($tabname){
796 global $QUESTION_EDITTABCAPS;
797 return $this->having_one_cap($QUESTION_EDITTABCAPS[$tabname]);
800 * Has at least one parent context got the cap $cap?
802 * @param string $cap capability
803 * @return boolean
805 function have_cap($cap){
806 return (count($this->having_cap($cap)));
810 * Has at least one parent context got one of the caps $caps?
812 * @param string $cap capability
813 * @return boolean
815 function have_one_cap($caps){
816 foreach ($caps as $cap){
817 if ($this->have_cap($cap)){
818 return true;
821 return false;
824 * Has at least one parent context got one of the caps for actions on $tabname
826 * @param string $tabname edit tab name
827 * @return boolean
829 function have_one_edit_tab_cap($tabname){
830 global $QUESTION_EDITTABCAPS;
831 return $this->have_one_cap($QUESTION_EDITTABCAPS[$tabname]);
834 * Throw error if at least one parent context hasn't got the cap $cap
836 * @param string $cap capability
838 function require_cap($cap){
839 if (!$this->have_cap($cap)){
840 print_error('nopermissions', '', '', $cap);
844 * Throw error if at least one parent context hasn't got one of the caps $caps
846 * @param array $cap capabilities
848 function require_one_cap($caps){
849 if (!$this->have_one_cap($caps)){
850 $capsstring = join($caps, ', ');
851 print_error('nopermissions', '', '', $capsstring);
855 * Throw error if at least one parent context hasn't got one of the caps $caps
857 * @param string $tabname edit tab name
859 function require_one_edit_tab_cap($tabname){
860 if (!$this->have_one_edit_tab_cap($tabname)){
861 print_error('nopermissions', '', '', 'access question edit tab '.$tabname);
866 //capabilities for each page of edit tab.
867 //this determines which contexts' categories are available. At least one
868 //page is displayed if user has one of the capability on at least one context
869 $QUESTION_EDITTABCAPS = array(
870 'editq' => array('moodle/question:add',
871 'moodle/question:editmine',
872 'moodle/question:editall',
873 'moodle/question:viewmine',
874 'moodle/question:viewall',
875 'moodle/question:usemine',
876 'moodle/question:useall',
877 'moodle/question:movemine',
878 'moodle/question:moveall'),
879 'questions'=>array('moodle/question:add',
880 'moodle/question:editmine',
881 'moodle/question:editall',
882 'moodle/question:viewmine',
883 'moodle/question:viewall',
884 'moodle/question:movemine',
885 'moodle/question:moveall'),
886 'categories'=>array('moodle/question:managecategory'),
887 'import'=>array('moodle/question:add'),
888 'export'=>array('moodle/question:viewall', 'moodle/question:viewmine'));
893 * Make sure user is logged in as required in this context.
895 function require_login_in_context($contextorid = null){
896 if (!is_object($contextorid)){
897 $context = get_context_instance_by_id($contextorid);
898 } else {
899 $context = $contextorid;
901 if ($context && ($context->contextlevel == CONTEXT_COURSE)) {
902 require_login($context->instanceid);
903 } else if ($context && ($context->contextlevel == CONTEXT_MODULE)) {
904 if ($cm = get_record('course_modules','id',$context->instanceid)) {
905 if (!$course = get_record('course', 'id', $cm->course)) {
906 error('Incorrect course.');
908 require_course_login($course, true, $cm);
910 } else {
911 error('Incorrect course module id.');
913 } else if ($context && ($context->contextlevel == CONTEXT_SYSTEM)) {
914 if (!empty($CFG->forcelogin)) {
915 require_login();
918 } else {
919 require_login();