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