Automatic installer.php lang files by installer_builder (20090119)
[moodle.git] / question / editlib.php
blob594a57d096571e77ec70bcb6cf821f392f20c739
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 list($categoryid, $contextid)= explode(',', $categoryandcontext);
167 $qtypemenu = question_type_menu();
169 $strcategory = get_string("category", "quiz");
170 $strquestion = get_string("question", "quiz");
171 $straddquestions = get_string("addquestions", "quiz");
172 $strimportquestions = get_string("importquestions", "quiz");
173 $strexportquestions = get_string("exportquestions", "quiz");
174 $strnoquestions = get_string("noquestions", "quiz");
175 $strselect = get_string("select", "quiz");
176 $strselectall = get_string("selectall", "quiz");
177 $strselectnone = get_string("selectnone", "quiz");
178 $strcreatenewquestion = get_string("createnewquestion", "quiz");
179 $strquestionname = get_string("questionname", "quiz");
180 $strdelete = get_string("delete");
181 $stredit = get_string("edit");
182 $strmove = get_string('moveqtoanothercontext', 'question');
183 $strview = get_string("view");
184 $straction = get_string("action");
185 $strrestore = get_string('restore');
187 $strtype = get_string("type", "quiz");
188 $strcreatemultiple = get_string("createmultiple", "quiz");
189 $strpreview = get_string("preview","quiz");
191 if (!$categoryid) {
192 echo "<p style=\"text-align:center;\"><b>";
193 print_string("selectcategoryabove", "quiz");
194 echo "</b></p>";
195 return;
198 if (!$category = get_record('question_categories', 'id', $categoryid, 'contextid', $contextid)) {
199 notify('Category not found!');
200 return;
202 $catcontext = get_context_instance_by_id($contextid);
203 $canadd = has_capability('moodle/question:add', $catcontext);
204 //check for capabilities on all questions in category, will also apply to sub cats.
205 $caneditall =has_capability('moodle/question:editall', $catcontext);
206 $canuseall =has_capability('moodle/question:useall', $catcontext);
207 $canmoveall =has_capability('moodle/question:moveall', $catcontext);
209 if ($cm AND $cm->modname == 'quiz') {
210 $quizid = $cm->instance;
211 } else {
212 $quizid = 0;
214 $returnurl = $pageurl->out();
215 $questionurl = new moodle_url("$CFG->wwwroot/question/question.php",
216 array('returnurl' => $returnurl));
217 if ($cm!==null){
218 $questionurl->param('cmid', $cm->id);
219 } else {
220 $questionurl->param('courseid', $COURSE->id);
222 $questionmoveurl = new moodle_url("$CFG->wwwroot/question/contextmoveq.php",
223 array('returnurl' => $returnurl));
224 if ($cm!==null){
225 $questionmoveurl->param('cmid', $cm->id);
226 } else {
227 $questionmoveurl->param('courseid', $COURSE->id);
229 echo '<div class="boxaligncenter">';
230 $formatoptions = new stdClass;
231 $formatoptions->noclean = true;
232 echo format_text($category->info, FORMAT_MOODLE, $formatoptions, $COURSE->id);
234 echo '<table><tr>';
236 if ($canadd) {
237 echo '<td valign="top" align="right">';
238 popup_form ($questionurl->out(false, array('category' => $category->id)).'&amp;qtype=', $qtypemenu, "addquestion", "", "choose", "", "", false, "self", "<strong>$strcreatenewquestion</strong>");
239 echo '</td><td valign="top" align="right">';
240 helpbutton("questiontypes", $strcreatenewquestion, "quiz");
241 echo '</td>';
243 else {
244 echo '<td>';
245 print_string('nopermissionadd', 'question');
246 echo '</td>';
249 echo '</tr></table>';
250 echo '</div>';
252 $categorylist = ($recurse) ? question_categorylist($category->id) : $category->id;
254 // hide-feature
255 $showhidden = $showhidden ? '' : " AND hidden = '0'";
257 if (!$totalnumber = count_records_select('question', "category IN ($categorylist) AND parent = '0' $showhidden")) {
258 echo "<p style=\"text-align:center;\">";
259 print_string("noquestions", "quiz");
260 echo "</p>";
261 return;
264 if (!$questions = get_records_select('question', "category IN ($categorylist) AND parent = '0' $showhidden", $sortorderdecoded, '*', $page*$perpage, $perpage)) {
265 // There are no questions on the requested page.
266 $page = 0;
267 if (!$questions = get_records_select('question', "category IN ($categorylist) AND parent = '0' $showhidden", $sortorderdecoded, '*', 0, $perpage)) {
268 // There are no questions at all
269 echo "<p style=\"text-align:center;\">";
270 print_string("noquestions", "quiz");
271 echo "</p>";
272 return;
276 print_paging_bar($totalnumber, $page, $perpage, $pageurl, 'qpage');
278 echo question_sort_options($pageurl, $sortorder);
281 echo '<form method="post" action="edit.php">';
282 echo '<fieldset class="invisiblefieldset" style="display: block;">';
283 echo '<input type="hidden" name="sesskey" value="'.$USER->sesskey.'" />';
284 echo $pageurl->hidden_params_out();
285 echo '<table id="categoryquestions" style="width: 100%"><tr>';
286 echo "<th style=\"white-space:nowrap;\" class=\"header\" scope=\"col\">$straction</th>";
288 echo "<th style=\"white-space:nowrap; text-align: left;\" class=\"header\" scope=\"col\">$strquestionname</th>
289 <th style=\"white-space:nowrap; text-align: right;\" class=\"header\" scope=\"col\">$strtype</th>";
290 echo "</tr>\n";
291 foreach ($questions as $question) {
292 $nameclass = '';
293 $textclass = '';
294 if ($question->hidden) {
295 $nameclass = 'dimmed_text';
296 $textclass = 'dimmed_text';
298 if ($showquestiontext) {
299 $nameclass .= ' header';
301 if ($nameclass) {
302 $nameclass = 'class="' . $nameclass . '"';
304 if ($textclass) {
305 $textclass = 'class="' . $textclass . '"';
308 echo "<tr>\n<td style=\"white-space:nowrap;\" $nameclass>\n";
310 $canuseq = question_has_capability_on($question, 'use', $question->category);
311 if (function_exists('module_specific_actions')) {
312 echo module_specific_actions($pageurl, $question->id, $cm->id, $canuseq);
315 // preview
316 if ($canuseq) {
317 $quizorcourseid = $quizid?('&amp;quizid=' . $quizid):('&amp;courseid=' .$COURSE->id);
318 link_to_popup_window('/question/preview.php?id=' . $question->id . $quizorcourseid, 'questionpreview',
319 "<img src=\"$CFG->pixpath/t/preview.gif\" class=\"iconsmall\" alt=\"$strpreview\" />",
320 0, 0, $strpreview, QUESTION_PREVIEW_POPUP_OPTIONS);
322 // edit, hide, delete question, using question capabilities, not quiz capabilieies
323 if (question_has_capability_on($question, 'edit', $question->category) || question_has_capability_on($question, 'move', $question->category)) {
324 echo "<a title=\"$stredit\" href=\"".$questionurl->out(false, array('id'=>$question->id))."\"><img
325 src=\"$CFG->pixpath/t/edit.gif\" alt=\"$stredit\" /></a>&nbsp;";
326 } elseif (question_has_capability_on($question, 'view', $question->category)){
327 echo "<a title=\"$strview\" href=\"".$questionurl->out(false, array('id'=>$question->id))."\"><img
328 src=\"$CFG->pixpath/i/info.gif\" alt=\"$strview\" /></a>&nbsp;";
331 if (question_has_capability_on($question, 'move', $question->category) && question_has_capability_on($question, 'view', $question->category)) {
332 echo "<a title=\"$strmove\" href=\"".$questionurl->out(false, array('id'=>$question->id, 'movecontext'=>1))."\"><img
333 src=\"$CFG->pixpath/t/move.gif\" alt=\"$strmove\" /></a>&nbsp;";
336 if (question_has_capability_on($question, 'edit', $question->category)) {
337 // hide-feature
338 if($question->hidden) {
339 echo "<a title=\"$strrestore\" href=\"edit.php?".$pageurl->get_query_string()."&amp;unhide=$question->id&amp;sesskey=$USER->sesskey\"><img
340 src=\"$CFG->pixpath/t/restore.gif\" alt=\"$strrestore\" /></a>";
341 } else {
342 echo "<a title=\"$strdelete\" href=\"edit.php?".$pageurl->get_query_string()."&amp;deleteselected=$question->id&amp;q$question->id=1\"><img
343 src=\"$CFG->pixpath/t/delete.gif\" alt=\"$strdelete\" /></a>";
346 if ($caneditall || $canmoveall || $canuseall){
347 echo "&nbsp;<input title=\"$strselect\" type=\"checkbox\" name=\"q$question->id\" value=\"1\" />";
349 echo "</td>\n";
351 echo "<td $nameclass>" . format_string($question->name) . "</td>\n";
352 echo "<td $nameclass style='text-align: right'>\n";
353 print_question_icon($question);
354 echo "</td>\n";
355 echo "</tr>\n";
356 if($showquestiontext){
357 echo '<tr><td colspan="3" ' . $textclass . '>';
358 $formatoptions = new stdClass;
359 $formatoptions->noclean = true;
360 $formatoptions->para = false;
361 echo format_text($question->questiontext, $question->questiontextformat,
362 $formatoptions, $COURSE->id);
363 echo "</td></tr>\n";
366 echo "</table>\n";
368 $paging = print_paging_bar($totalnumber, $page, $perpage, $pageurl, 'qpage', false, true);
369 if ($totalnumber > DEFAULT_QUESTIONS_PER_PAGE) {
370 if ($perpage == DEFAULT_QUESTIONS_PER_PAGE) {
371 $showall = '<a href="edit.php?'.$pageurl->get_query_string(array('qperpage'=>1000)).'">'.get_string('showall', 'moodle', $totalnumber).'</a>';
372 } else {
373 $showall = '<a href="edit.php?'.$pageurl->get_query_string(array('qperpage'=>DEFAULT_QUESTIONS_PER_PAGE)).'">'.get_string('showperpage', 'moodle', DEFAULT_QUESTIONS_PER_PAGE).'</a>';
375 if ($paging) {
376 $paging = substr($paging, 0, strrpos($paging, '</div>'));
377 $paging .= "<br />$showall</div>";
378 } else {
379 $paging = "<div class='paging'>$showall</div>";
382 echo $paging;
384 if ($caneditall || $canmoveall || $canuseall){
385 echo '<a href="javascript:select_all_in(\'TABLE\',null,\'categoryquestions\');">'.$strselectall.'</a> /'.
386 ' <a href="javascript:deselect_all_in(\'TABLE\',null,\'categoryquestions\');">'.$strselectnone.'</a>';
387 echo '<br />';
388 echo '<strong>&nbsp;'.get_string('withselected', 'quiz').':</strong><br />';
390 if (function_exists('module_specific_buttons')) {
391 echo module_specific_buttons($cm->id);
393 // print delete and move selected question
394 if ($caneditall) {
395 echo '<input type="submit" name="deleteselected" value="'.$strdelete."\" />\n";
397 if ($canmoveall && count($addcontexts)) {
398 echo '<input type="submit" name="move" value="'.get_string('moveto', 'quiz')."\" />\n";
399 question_category_select_menu($addcontexts, false, 0, "$category->id,$category->contextid");
402 if (function_exists('module_specific_controls') && $canuseall) {
403 echo module_specific_controls($totalnumber, $recurse, $category, $cm->id);
406 echo '</fieldset>';
407 echo "</form>\n";
409 function question_sort_options($pageurl, $sortorder){
410 global $USER;
411 //sort options
412 $html = "<div class=\"mdl-align\">";
413 $html .= '<form method="post" action="edit.php">';
414 $html .= '<fieldset class="invisiblefieldset" style="display: block;">';
415 $html .= '<input type="hidden" name="sesskey" value="'.$USER->sesskey.'" />';
416 $html .= $pageurl->hidden_params_out(array('qsortorder'));
417 $sortoptions = array('alpha' => get_string("sortalpha", "quiz"),
418 'typealpha' => get_string("sorttypealpha", "quiz"),
419 'age' => get_string("sortage", "quiz"));
420 $html .= choose_from_menu ($sortoptions, 'qsortorder', $sortorder, false, 'this.form.submit();', '0', true);
421 $html .= '<noscript><div><input type="submit" value="'.get_string("sortsubmit", "quiz").'" /></div></noscript>';
422 $html .= '</fieldset>';
423 $html .= "</form>\n";
424 $html .= "</div>\n";
425 return $html;
428 function question_showbank_actions($pageurl, $cm){
429 global $CFG, $COURSE;
430 /// Now, check for commands on this page and modify variables as necessary
431 if (optional_param('move', false, PARAM_BOOL) and confirm_sesskey()) { /// Move selected questions to new category
432 $category = required_param('category', PARAM_SEQUENCE);
433 list($tocategoryid, $contextid) = explode(',', $category);
434 if (! $tocategory = get_record('question_categories', 'id', $tocategoryid, 'contextid', $contextid)) {
435 error('Could not find category record');
437 $tocontext = get_context_instance_by_id($contextid);
438 require_capability('moodle/question:add', $tocontext);
439 $rawdata = (array) data_submitted();
440 $questionids = array();
441 foreach ($rawdata as $key => $value) { // Parse input for question ids
442 if (preg_match('!^q([0-9]+)$!', $key, $matches)) {
443 $key = $matches[1];
444 $questionids[] = $key;
447 if ($questionids){
448 $questionidlist = join($questionids, ',');
449 $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";
450 if (!$questions = get_records_sql($sql)){
451 print_error('questiondoesnotexist', 'question', $pageurl->out());
453 $checkforfiles = false;
454 foreach ($questions as $question){
455 //check capabilities
456 question_require_capability_on($question, 'move');
457 $fromcontext = get_context_instance_by_id($question->contextid);
458 if (get_filesdir_from_context($fromcontext) != get_filesdir_from_context($tocontext)){
459 $checkforfiles = true;
462 $returnurl = $pageurl->out(false, array('category'=>"$tocategoryid,$contextid"));
463 if (!$checkforfiles){
464 if (!question_move_questions_to_category(implode(',', $questionids), $tocategory->id)) {
465 print_error('errormovingquestions', 'question', $returnurl, $questionids);
467 redirect($returnurl);
468 } else {
469 $movecontexturl = new moodle_url($CFG->wwwroot.'/question/contextmoveq.php',
470 array('returnurl' => $returnurl,
471 'ids'=>$questionidlist,
472 'tocatid'=> $tocategoryid));
473 if ($cm){
474 $movecontexturl->param('cmid', $cm->id);
475 } else {
476 $movecontexturl->param('courseid', $COURSE->id);
478 redirect($movecontexturl->out());
483 if (optional_param('deleteselected', false, PARAM_BOOL)) { // delete selected questions from the category
484 if (($confirm = optional_param('confirm', '', PARAM_ALPHANUM)) and confirm_sesskey()) { // teacher has already confirmed the action
485 $deleteselected = required_param('deleteselected');
486 if ($confirm == md5($deleteselected)) {
487 if ($questionlist = explode(',', $deleteselected)) {
488 // for each question either hide it if it is in use or delete it
489 foreach ($questionlist as $questionid) {
490 question_require_capability_on($questionid, 'edit');
491 if (record_exists('quiz_question_instances', 'question', $questionid)) {
492 if (!set_field('question', 'hidden', 1, 'id', $questionid)) {
493 question_require_capability_on($questionid, 'edit');
494 error('Was not able to hide question');
496 } else {
497 delete_question($questionid);
501 redirect($pageurl->out());
502 } else {
503 error("Confirmation string was incorrect");
508 // Unhide a question
509 if(($unhide = optional_param('unhide', '', PARAM_INT)) and confirm_sesskey()) {
510 question_require_capability_on($unhide, 'edit');
511 if(!set_field('question', 'hidden', 0, 'id', $unhide)) {
512 error("Failed to unhide the question.");
514 redirect($pageurl->out());
519 * Shows the question bank editing interface.
521 * The function also processes a number of actions:
523 * Actions affecting the question pool:
524 * move Moves a question to a different category
525 * deleteselected Deletes the selected questions from the category
526 * Other actions:
527 * category Chooses the category
528 * displayoptions Sets display options
530 * @author Martin Dougiamas and many others. This has recently been extensively
531 * rewritten by Gustav Delius and other members of the Serving Mathematics project
532 * {@link http://maths.york.ac.uk/serving_maths}
533 * @param moodle_url $pageurl object representing this pages url.
535 function question_showbank($tabname, $contexts, $pageurl, $cm, $page, $perpage, $sortorder, $sortorderdecoded, $cat, $recurse, $showhidden, $showquestiontext){
536 global $COURSE;
538 if (optional_param('deleteselected', false, PARAM_BOOL)){ // teacher still has to confirm
539 // make a list of all the questions that are selected
540 $rawquestions = $_REQUEST; // This code is called by both POST forms and GET links, so cannot use data_submitted.
541 $questionlist = ''; // comma separated list of ids of questions to be deleted
542 $questionnames = ''; // string with names of questions separated by <br /> with
543 // an asterix in front of those that are in use
544 $inuse = false; // set to true if at least one of the questions is in use
545 foreach ($rawquestions as $key => $value) { // Parse input for question ids
546 if (preg_match('!^q([0-9]+)$!', $key, $matches)) {
547 $key = $matches[1];
548 $questionlist .= $key.',';
549 question_require_capability_on($key, 'edit');
550 if (record_exists('quiz_question_instances', 'question', $key)) {
551 $questionnames .= '* ';
552 $inuse = true;
554 $questionnames .= get_field('question', 'name', 'id', $key).'<br />';
557 if (!$questionlist) { // no questions were selected
558 redirect($pageurl->out());
560 $questionlist = rtrim($questionlist, ',');
562 // Add an explanation about questions in use
563 if ($inuse) {
564 $questionnames .= '<br />'.get_string('questionsinuse', 'quiz');
566 notice_yesno(get_string("deletequestionscheck", "quiz", $questionnames),
567 $pageurl->out_action(array('deleteselected'=>$questionlist, 'confirm'=>md5($questionlist))),
568 $pageurl->out_action());
570 echo '</td></tr>';
571 echo '</table>';
572 print_footer($COURSE);
573 exit;
577 // starts with category selection form
578 print_box_start('generalbox questionbank');
579 print_heading(get_string('questionbank', 'question'), '', 2);
580 question_category_form($contexts->having_one_edit_tab_cap($tabname), $pageurl, $cat, $recurse, $showhidden, $showquestiontext);
582 // continues with list of questions
583 question_list($contexts->having_one_edit_tab_cap($tabname), $pageurl, $cat, isset($cm) ? $cm : null,
584 $recurse, $page, $perpage, $showhidden, $sortorder, $sortorderdecoded, $showquestiontext,
585 $contexts->having_cap('moodle/question:add'));
587 print_box_end();
590 * Common setup for all pages for editing questions.
591 * @param string $edittab code for this edit tab
592 * @param boolean $requirecmid require cmid? default false
593 * @param boolean $requirecourseid require courseid, if cmid is not given? default true
594 * @return array $thispageurl, $contexts, $cmid, $cm, $module, $pagevars
596 function question_edit_setup($edittab, $requirecmid = false, $requirecourseid = true){
597 global $COURSE, $QUESTION_EDITTABCAPS;
599 //$thispageurl is used to construct urls for all question edit pages we link to from this page. It contains an array
600 //of parameters that are passed from page to page.
601 $thispageurl = new moodle_url();
602 if ($requirecmid){
603 $cmid =required_param('cmid', PARAM_INT);
604 } else {
605 $cmid = optional_param('cmid', 0, PARAM_INT);
607 if ($cmid){
608 list($module, $cm) = get_module_from_cmid($cmid);
609 $courseid = $cm->course;
610 $thispageurl->params(compact('cmid'));
611 require_login($courseid, false, $cm);
612 $thiscontext = get_context_instance(CONTEXT_MODULE, $cmid);
613 } else {
614 $module = null;
615 $cm = null;
616 if ($requirecourseid){
617 $courseid = required_param('courseid', PARAM_INT);
618 } else {
619 $courseid = optional_param('courseid', 0, PARAM_INT);
621 if ($courseid){
622 $thispageurl->params(compact('courseid'));
623 require_login($courseid, false);
624 $thiscontext = get_context_instance(CONTEXT_COURSE, $courseid);
625 } else {
626 $thiscontext = null;
630 if ($thiscontext){
631 $contexts = new question_edit_contexts($thiscontext);
632 $contexts->require_one_edit_tab_cap($edittab);
634 } else {
635 $contexts = null;
640 $pagevars['qpage'] = optional_param('qpage', -1, PARAM_INT);
642 //pass 'cat' from page to page and when 'category' comes from a drop down menu
643 //then we also reset the qpage so we go to page 1 of
644 //a new cat.
645 $pagevars['cat'] = optional_param('cat', 0, PARAM_SEQUENCE);// if empty will be set up later
646 if ($category = optional_param('category', 0, PARAM_SEQUENCE)){
647 if ($pagevars['cat'] != $category){ // is this a move to a new category?
648 $pagevars['cat'] = $category;
649 $pagevars['qpage'] = 0;
652 if ($pagevars['cat']){
653 $thispageurl->param('cat', $pagevars['cat']);
655 if ($pagevars['qpage'] > -1) {
656 $thispageurl->param('qpage', $pagevars['qpage']);
657 } else {
658 $pagevars['qpage'] = 0;
661 $pagevars['qperpage'] = optional_param('qperpage', -1, PARAM_INT);
662 if ($pagevars['qperpage'] > -1) {
663 $thispageurl->param('qperpage', $pagevars['qperpage']);
664 } else {
665 $pagevars['qperpage'] = DEFAULT_QUESTIONS_PER_PAGE;
668 $sortoptions = array('alpha' => 'name, qtype ASC',
669 'typealpha' => 'qtype, name ASC',
670 'age' => 'id ASC');
672 if ($sortorder = optional_param('qsortorder', '', PARAM_ALPHA)) {
673 $pagevars['qsortorderdecoded'] = $sortoptions[$sortorder];
674 $pagevars['qsortorder'] = $sortorder;
675 $thispageurl->param('qsortorder', $sortorder);
676 } else {
677 $pagevars['qsortorderdecoded'] = $sortoptions['typealpha'];
678 $pagevars['qsortorder'] = 'typealpha';
681 $defaultcategory = question_make_default_categories($contexts->all());
683 $contextlistarr = array();
684 foreach ($contexts->having_one_edit_tab_cap($edittab) as $context){
685 $contextlistarr[] = "'$context->id'";
687 $contextlist = join($contextlistarr, ' ,');
688 if (!empty($pagevars['cat'])){
689 $catparts = explode(',', $pagevars['cat']);
690 if (!$catparts[0] || (FALSE !== array_search($catparts[1], $contextlistarr)) || !count_records_select("question_categories", "id = '".$catparts[0]."' AND contextid = $catparts[1]")) {
691 print_error('invalidcategory', 'quiz');
693 } else {
694 $category = $defaultcategory;
695 $pagevars['cat'] = "$category->id,$category->contextid";
698 if(($recurse = optional_param('recurse', -1, PARAM_BOOL)) != -1) {
699 $pagevars['recurse'] = $recurse;
700 $thispageurl->param('recurse', $recurse);
701 } else {
702 $pagevars['recurse'] = 1;
705 if(($showhidden = optional_param('showhidden', -1, PARAM_BOOL)) != -1) {
706 $pagevars['showhidden'] = $showhidden;
707 $thispageurl->param('showhidden', $showhidden);
708 } else {
709 $pagevars['showhidden'] = 0;
712 if(($showquestiontext = optional_param('showquestiontext', -1, PARAM_BOOL)) != -1) {
713 $pagevars['showquestiontext'] = $showquestiontext;
714 $thispageurl->param('showquestiontext', $showquestiontext);
715 } else {
716 $pagevars['showquestiontext'] = 0;
719 //category list page
720 $pagevars['cpage'] = optional_param('cpage', 1, PARAM_INT);
721 if ($pagevars['cpage'] < 1) {
722 $pagevars['cpage'] = 1;
724 if ($pagevars['cpage'] != 1){
725 $thispageurl->param('cpage', $pagevars['cpage']);
729 return array($thispageurl, $contexts, $cmid, $cm, $module, $pagevars);
731 class question_edit_contexts{
732 var $allcontexts;
734 * @param current context
736 function question_edit_contexts($thiscontext){
737 $pcontextids = get_parent_contexts($thiscontext);
738 $contexts = array($thiscontext);
739 foreach ($pcontextids as $pcontextid){
740 $contexts[] = get_context_instance_by_id($pcontextid);
742 $this->allcontexts = $contexts;
745 * @return array all parent contexts
747 function all(){
748 return $this->allcontexts;
751 * @return object lowest context which must be either the module or course context
753 function lowest(){
754 return $this->allcontexts[0];
757 * @param string $cap capability
758 * @return array parent contexts having capability, zero based index
760 function having_cap($cap){
761 $contextswithcap = array();
762 foreach ($this->allcontexts as $context){
763 if (has_capability($cap, $context)){
764 $contextswithcap[] = $context;
767 return $contextswithcap;
770 * @param array $caps capabilities
771 * @return array parent contexts having at least one of $caps, zero based index
773 function having_one_cap($caps){
774 $contextswithacap = array();
775 foreach ($this->allcontexts as $context){
776 foreach ($caps as $cap){
777 if (has_capability($cap, $context)){
778 $contextswithacap[] = $context;
779 break; //done with caps loop
783 return $contextswithacap;
786 * @param string $tabname edit tab name
787 * @return array parent contexts having at least one of $caps, zero based index
789 function having_one_edit_tab_cap($tabname){
790 global $QUESTION_EDITTABCAPS;
791 return $this->having_one_cap($QUESTION_EDITTABCAPS[$tabname]);
794 * Has at least one parent context got the cap $cap?
796 * @param string $cap capability
797 * @return boolean
799 function have_cap($cap){
800 return (count($this->having_cap($cap)));
804 * Has at least one parent context got one of the caps $caps?
806 * @param string $cap capability
807 * @return boolean
809 function have_one_cap($caps){
810 foreach ($caps as $cap){
811 if ($this->have_cap($cap)){
812 return true;
815 return false;
818 * Has at least one parent context got one of the caps for actions on $tabname
820 * @param string $tabname edit tab name
821 * @return boolean
823 function have_one_edit_tab_cap($tabname){
824 global $QUESTION_EDITTABCAPS;
825 return $this->have_one_cap($QUESTION_EDITTABCAPS[$tabname]);
828 * Throw error if at least one parent context hasn't got the cap $cap
830 * @param string $cap capability
832 function require_cap($cap){
833 if (!$this->have_cap($cap)){
834 print_error('nopermissions', '', '', $cap);
838 * Throw error if at least one parent context hasn't got one of the caps $caps
840 * @param array $cap capabilities
842 function require_one_cap($caps){
843 if (!$this->have_one_cap($caps)){
844 $capsstring = join($caps, ', ');
845 print_error('nopermissions', '', '', $capsstring);
849 * Throw error if at least one parent context hasn't got one of the caps $caps
851 * @param string $tabname edit tab name
853 function require_one_edit_tab_cap($tabname){
854 if (!$this->have_one_edit_tab_cap($tabname)){
855 print_error('nopermissions', '', '', 'access question edit tab '.$tabname);
860 //capabilities for each page of edit tab.
861 //this determines which contexts' categories are available. At least one
862 //page is displayed if user has one of the capability on at least one context
863 $QUESTION_EDITTABCAPS = array(
864 'editq' => array('moodle/question:add',
865 'moodle/question:editmine',
866 'moodle/question:editall',
867 'moodle/question:viewmine',
868 'moodle/question:viewall',
869 'moodle/question:usemine',
870 'moodle/question:useall',
871 'moodle/question:movemine',
872 'moodle/question:moveall'),
873 'questions'=>array('moodle/question:add',
874 'moodle/question:editmine',
875 'moodle/question:editall',
876 'moodle/question:viewmine',
877 'moodle/question:viewall',
878 'moodle/question:movemine',
879 'moodle/question:moveall'),
880 'categories'=>array('moodle/question:managecategory'),
881 'import'=>array('moodle/question:add'),
882 'export'=>array('moodle/question:viewall', 'moodle/question:viewmine'));
887 * Make sure user is logged in as required in this context.
889 function require_login_in_context($contextorid = null){
890 if (!is_object($contextorid)){
891 $context = get_context_instance_by_id($contextorid);
892 } else {
893 $context = $contextorid;
895 if ($context && ($context->contextlevel == CONTEXT_COURSE)) {
896 require_login($context->instanceid);
897 } else if ($context && ($context->contextlevel == CONTEXT_MODULE)) {
898 if ($cm = get_record('course_modules','id',$context->instanceid)) {
899 if (!$course = get_record('course', 'id', $cm->course)) {
900 error('Incorrect course.');
902 require_course_login($course, true, $cm);
904 } else {
905 error('Incorrect course module id.');
907 } else if ($context && ($context->contextlevel == CONTEXT_SYSTEM)) {
908 if (!empty($CFG->forcelogin)) {
909 require_login();
912 } else {
913 require_login();