Updated the HEAD build version to 20090122
[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
46795afc 130abstract class question_bank_column_base {
5bd22790 131 protected $qbank;
132
133 /**
134 * Constructor.
135 * @param $qbank the question_bank_view we are helping to render.
136 */
137 public function __construct(question_bank_view $qbank) {
138 $this->qbank = $qbank;
139 $this->init();
140 }
141
142 /**
143 * A chance for subclasses to initialise themselves, for example to load lang strings,
144 * without having to override the constructor.
145 */
146 protected function init() {
147 }
46795afc 148
149 /**
150 * Output the column header cell.
151 * @param integer $currentsort 0 for none. 1 for normal sort, -1 for reverse sort.
152 */
5bd22790 153 public function display_header() {
154 echo '<th class=header ' . $this->get_name() . '" scope="col">';
155 $sortable = $this->is_sortable();
156 $name = $this->get_name();
157 $title = $this->get_title();
158 if (is_array($sortable)) {
159 if ($title) {
160 echo '<div class="title">' . $title . '</div>';
161 }
162 $links = array();
163 foreach ($sortable as $subsort => $details) {
164 $links[] = $this->make_sort_link($name . '_' . $subsort, $details['title'], !empty($details['reverse']));
165 }
166 echo implode(' / ', $links);
167 } else if ($sortable) {
168 echo $this->make_sort_link($name, $this->qbank->get_sort($name), $title);
169 } else {
170 echo $title;
171 }
172 echo "</th>\n";
173 }
174
175 /**
176 * Title for this column. Not used if is_sortable returns an array.
177 * @param object $question the row from the $question table, augmented with extra information.
178 * @param string $rowclasses CSS class names that should be applied to this row of output.
179 */
180 protected function get_title() {
181 return '';
182 }
183
184 /**
185 * Get a link that changes the sort order, and indicates the current sort state.
186 * @param $name internal name used for this type of sorting.
187 * @param $currentsort the current sort order -1, 0, 1 for descending, none, ascending.
188 * @param $title the link text.
189 * @param $defaultreverse whether the default sort order for this column is descending, rather than ascending.
190 * @return string HTML fragment.
191 */
192 protected function make_sort_link($name, $currentsort, $title, $defaultreverse = false) {
193 $newsortreverse = $defaultreverse;
194 if ($currentsort) {
195 $newsortreverse = $currentsort > 0;
196 }
197 if ($newsortreverse) {
198 $tip = get_string('sortbyxreverse', '', $title);
199 } else {
200 $tip = get_string('sortbyx', '', $title);
201 }
202 echo '<a href="' . $this->qbank->new_sort_url($name, $newsortreverse) . '" title="' . $tip . '">';
203 echo $title;
204 if ($currentsort) {
205 echo $this->get_sort_icon($currentsort < 0);
206 }
207 echo '</a>';
208 }
209
210 /**
211 * Get an icon representing the corrent sort state.
212 * @param $reverse sort is descending, not ascending.
213 * @return string HTML image tag.
214 */
215 protected function get_sort_icon($reverse) {
216 global $CFG;
217 if ($reverse) {
218 return ' <img src="' . $CFG->pixpath . '/t/up.gif" alt="' . get_string('desc') . '" />';
219 } else {
220 return ' <img src="' . $CFG->pixpath . '/t/down.gif" alt="' . get_string('asc') . '" />';
221 }
46795afc 222 }
223
224 /**
225 * Output this column.
226 * @param object $question the row from the $question table, augmented with extra information.
227 * @param string $rowclasses CSS class names that should be applied to this row of output.
228 */
229 public function display($question, $rowclasses) {
230 $this->display_start($question, $rowclasses);
231 $this->display_content($question, $rowclasses);
232 $this->display_end($question, $rowclasses);
233 }
234
235 protected function display_start($question, $rowclasses) {
5bd22790 236 echo '<td class="' . $this->get_name() . '">';
46795afc 237 }
238
239 /**
240 * @param object $question the row from the $question table, augmented with extra information.
b221dc6f 241 * @return string internal name for this column. Used as a CSS class name,
242 * and to store information about the current sort. Must match PARAM_ALPHA.
46795afc 243 */
babdcb40 244 abstract public function get_name();
46795afc 245
246 /**
247 * Output the contents of this column.
248 * @param object $question the row from the $question table, augmented with extra information.
249 * @param string $rowclasses CSS class names that should be applied to this row of output.
250 */
251 abstract protected function display_content($question, $rowclasses);
252
253 protected function display_end($question, $rowclasses) {
5bd22790 254 echo "</td>\n";
46795afc 255 }
256
257 /**
258 * Return an array 'table_alias' => 'JOIN clause' to bring in any data that
259 * this column required.
260 *
261 * The return values for all the columns will be checked. It is OK if two
262 * columns join in the same table with the same alias and identical JOIN clauses.
263 * If to columns try to use the same alias with different joins, you get an error.
264 * The only table included by default is the question table, which is aliased to 'q'.
265 *
b221dc6f 266 * It is importnat that your join simply adds additional data (or NULLs) to the
267 * existing rows of the query. It must not cause additional rows.
268 *
46795afc 269 * @return array 'table_alias' => 'JOIN clause'
270 */
271 public function get_extra_joins() {
272 return array();
273 }
274
275 /**
276 * @return array fields required. use table alias 'q' for the question table, or one of the
277 * ones from get_extra_joins. Every field requested must specify a table prefix.
278 */
279 public function get_required_fields() {
280 return array();
281 }
282
283 /**
284 * Can this column be sorted on? You can return either:
285 * + false for no (the default),
5bd22790 286 * + a field name, if sorting this column corresponds to sorting on that datbase field.
287 * + an array of subnames to sort on as follows
288 * return array(
289 * 'firstname' => array('field' => 'uc.firstname', 'title' => get_string('firstname')),
290 * 'lastname' => array('field' => 'uc.lastname', 'field' => get_string('lastname')),
291 * );
292 * As well as field, and field, you can also add 'revers' => 1 if you want the default sort
293 * order to be DESC.
294 * @return mixed as above.
46795afc 295 */
296 public function is_sortable() {
297 return false;
298 }
299
300 /**
301 * Helper method for building sort clauses.
302 * @param boolean $reverse whether the normal direction should be reversed.
303 * @param string $normaldir 'ASC' or 'DESC'
304 * @return string 'ASC' or 'DESC'
305 */
5bd22790 306 protected function sortorder($reverse) {
307 if ($reverse) {
308 return ' DESC';
309 } else {
310 return ' ASC';
46795afc 311 }
312 }
313
314 /**
315 * @param $reverse Whether to sort in the reverse of the default sort order.
316 * @param $subsort if is_sortable returns an array of subnames, then this will be
317 * one of those. Otherwise will be empty.
318 * @return string some SQL to go in the order by clause.
319 */
320 public function sort_expression($reverse, $subsort) {
5bd22790 321 $sortable = $this->is_sortable();
322 if (is_array($sortable)) {
323 if (array_key_exists($subsort, $sortable)) {
324 return $sortable[$sortable]['field'] . $this->sortorder($reverse, !empty($sortable[$sortable]['reverse']));
325 } else {
326 throw new coding_exception('Unexpected $subsort type: ' . $subsort);
327 }
328 } else if ($sortable) {
329 return $sortable . $this->sortorder($reverse);
330 } else {
331 throw new coding_exception('sort_expression called on a non-sortable column.');
332 }
46795afc 333 }
334}
335
336/**
337 * A column with a checkbox for each question with name q{questionid}.
338 */
339class question_bank_checkbox_column extends question_bank_column_base {
340 protected $strselect;
341
5bd22790 342 public function init() {
46795afc 343 $this->strselect = get_string('select', 'quiz');
344 }
345
babdcb40 346 public function get_name() {
46795afc 347 return 'checkbox';
348 }
349
5bd22790 350 protected function get_title() {
351 return '<input type="checkbox" disabled="disabled" />';
352 }
353
46795afc 354 protected function display_content($question, $rowclasses) {
355 echo '<input title="' . $this->strselect . '" type="checkbox" name="q' .
356 $question->id . '" id="checkq' . $question->id . '" value="1" />';
357 }
358
359 public function get_required_fields() {
360 return array('q.id');
361 }
362}
363
364/**
365 * A column type for the name of the question type.
366 */
367class question_bank_question_type_column extends question_bank_column_base {
babdcb40 368 public function get_name() {
46795afc 369 return 'qtype';
370 }
371
5bd22790 372 protected function get_title() {
373 return get_string('qtypeveryshort', 'question');
374 }
375
46795afc 376 protected function display_content($question, $rowclasses) {
377 echo print_question_icon($question);
378 }
379
380 public function get_required_fields() {
381 return array('q.qtype');
382 }
383
384 public function is_sortable() {
5bd22790 385 return 'q.qtype';
46795afc 386 }
387}
388
389/**
390 * A column type for the name of the question name.
391 */
392class question_bank_question_name_column extends question_bank_column_base {
babdcb40 393 public function get_name() {
46795afc 394 return 'questionname';
395 }
396
5bd22790 397 protected function get_title() {
398 return get_string('question');
399 }
400
46795afc 401 protected function display_content($question, $rowclasses) {
402 echo format_string($question->name);
403 }
404
405 public function get_required_fields() {
406 return array('q.name');
407 }
408
409 public function is_sortable() {
5bd22790 410 return 'q.name';
46795afc 411 }
412}
413
414/**
415 * A column type for the name of the question creator.
416 */
417class question_bank_creator_name_column extends question_bank_column_base {
babdcb40 418 public function get_name() {
46795afc 419 return 'creatorname';
420 }
421
5bd22790 422 protected function get_title() {
423 return get_string('createdby', 'question');
424 }
425
46795afc 426 protected function display_content($question, $rowclasses) {
427 if (!empty($question->creatorfirstname) && !empty($question->creatorlastname)) {
428 $u = new stdClass;
429 $u->firstname = $question->creatorfirstname;
430 $u->lastname = $question->creatorlastname;
431 echo fullname($u);
432 }
433 }
434
435 public function get_extra_joins() {
436 return array('uc' => 'LEFT JOIN {user} uc ON uc.id = q.createdby');
437 }
438
439 public function get_required_fields() {
440 return array('uc.firstname AS creatorfirstname', 'uc.lastname AS creatorlastname');
441 }
442
443 public function is_sortable() {
5bd22790 444 return array(
445 'firstname' => array('field' => 'uc.firstname', 'title' => get_string('firstname')),
446 'lastname' => array('field' => 'uc.lastname', 'title' => get_string('lastname')),
447 );
46795afc 448 }
449}
450
451/**
452 * A column type for the name of the question last modifier.
453 */
454class question_bank_modifier_name_column extends question_bank_column_base {
babdcb40 455 public function get_name() {
46795afc 456 return 'modifiername';
457 }
458
5bd22790 459 protected function get_title() {
460 return get_string('lastmodifiedby', 'question');
461 }
462
46795afc 463 protected function display_content($question, $rowclasses) {
464 if (!empty($question->modifierfirstname) && !empty($question->modifierlastname)) {
465 $u = new stdClass;
466 $u->firstname = $question->modifierfirstname;
467 $u->lastname = $question->modifierlastname;
468 echo fullname($u);
469 }
470 }
471
472 public function get_extra_joins() {
473 return array('um' => 'LEFT JOIN {user} um ON um.id = q.modifiedby');
474 }
475
476 public function get_required_fields() {
477 return array('um.firstname AS modifierfirstname', 'um.lastname AS modifierlastname');
478 }
479
480 public function is_sortable() {
5bd22790 481 return array(
482 'firstname' => array('field' => 'um.firstname', 'title' => get_string('firstname')),
483 'lastname' => array('field' => 'um.lastname', 'title' => get_string('lastname')),
484 );
46795afc 485 }
486}
487
488/**
489 * A base class for actions that are an icon that lets you manipulate the question in some way.
490 */
491abstract class question_bank_action_column_base extends question_bank_column_base {
5bd22790 492
493 protected function get_title() {
494 return '&#160;';
495 }
496
46795afc 497 protected function print_icon($icon, $title, $url) {
498 global $CFG;
499 echo '<a title="' . $title . '" href="' . $url . '">
500 <img src="' . $CFG->pixpath . '/t/' . $icon . '" class="iconsmall" alt="' . $title . '" /></a>';
501 }
502
503 public function get_required_fields() {
504 return array('q.id');
505 }
506}
507
508class question_bank_edit_action_column extends question_bank_action_column_base {
509 protected $stredit;
510 protected $strview;
46795afc 511
5bd22790 512 public function init() {
513 parent::init();
46795afc 514 $this->stredit = get_string('edit');
515 $this->strview = get_string('view');
516 }
517
babdcb40 518 public function get_name() {
46795afc 519 return 'editaction';
520 }
521
522 protected function display_content($question, $rowclasses) {
523 if (question_has_capability_on($question, 'edit') ||
524 question_has_capability_on($question, 'move')) {
5bd22790 525 $this->print_icon('edit', $this->stredit, $this->qbank->edit_question_url($question->id));
46795afc 526 } else {
5bd22790 527 $this->print_icon('info', $this->strview, $this->qbank->edit_question_url($question->id));
46795afc 528 }
529 }
530}
531
532class question_bank_preview_action_column extends question_bank_action_column_base {
533 protected $strpreview;
46795afc 534
5bd22790 535 public function init() {
536 parent::init();
46795afc 537 $this->stredit = get_string('preview');
538 }
539
babdcb40 540 public function get_name() {
46795afc 541 return 'previewaction';
542 }
543
544 protected function display_content($question, $rowclasses) {
545 if (question_has_capability_on($question, 'use')) {
5bd22790 546 link_to_popup_window($this->qbank->preview_question_url($question->id), 'questionpreview',
46795afc 547 ' <img src="' . $CFG->pixpath . '/t/preview.gif" class="iconsmall" alt="' . $this->strpreview . '" />',
548 0, 0, $this->strpreview, QUESTION_PREVIEW_POPUP_OPTIONS);
549 }
550 }
551
552 public function get_required_fields() {
553 return array('q.id');
554 }
555}
556
557class question_bank_move_action_column extends question_bank_action_column_base {
558 protected $strmove;
46795afc 559
5bd22790 560 public function init() {
561 parent::init();
46795afc 562 $this->strmove = get_string('move');
563 }
564
babdcb40 565 public function get_name() {
566 return 'moveaction';
46795afc 567 }
568
569 protected function display_content($question, $rowclasses) {
570 if (question_has_capability_on($question, 'move')) {
5bd22790 571 $this->print_icon('move', $this->strmove, $this->qbank->edit_question_url($question->id));
46795afc 572 }
573 }
574}
575
576/**
577 * action to delete (or hide) a question, or restore a previously hidden question.
578 */
579class question_bank_delete_action_column extends question_bank_action_column_base {
580 protected $strdelete;
581 protected $strrestore;
46795afc 582
5bd22790 583 public function init() {
584 parent::init();
46795afc 585 $this->strdelete = get_string('delete');
586 $this->strrestore = get_string('restore');
587 }
588
babdcb40 589 public function get_name() {
46795afc 590 return 'deleteaction';
591 }
592
593 protected function display_content($question, $rowclasses) {
594 if (question_has_capability_on($question, 'edit')) {
595 if ($question->hidden) {
5bd22790 596 $this->print_icon('restore', $this->strrestore, $this->qbank->base_url()->out(false, array('unhide' => $question->id)));
46795afc 597 } else {
598 $this->print_icon('restore', $this->strrestore,
5bd22790 599 $this->qbank->base_url()->out(false, array('deleteselected' => $question->id, 'q' . $question->id => 1)));
46795afc 600 }
601 }
602 }
603
604 public function get_required_fields() {
605 return array('q.id', 'q.hidden');
606 }
607}
608
4fbfd971 609/**
f4b879dd 610 * This class prints a view of the question bank, including
611 * + Some controls to allow users to to select what is displayed.
612 * + A list of questions as a table.
613 * + Further controls to do things with the questions.
614 *
615 * This class gives a basic view, and provides plenty of hooks where subclasses
616 * can override parts of the display.
617 *
618 * The list of questions presented as a table is generated by creating a list of
619 * question_bank_column objects, one for each 'column' to be displayed. These
620 * manage
621 * + outputting the contents of that column, given a $question object, but also
622 * + generating the right fragments of SQL to ensure the necessary data is present,
623 * and sorted in the right order.
624 * + outputting table headers.
4fbfd971 625 */
f4b879dd 626class question_bank_view {
5bd22790 627 protected $baseurl;
628 protected $editquestionurl;
629 protected $quizorcourseid;
630 protected $contexts;
631 protected $cm;
b221dc6f 632 protected $knowncolumntypes;
633 protected $visiblecolumns;
634 protected $requiredcolumns;
635 protected $sort;
636 protected $countsql;
637 protected $loadsql;
5bd22790 638
639 public function __construct($contexts, $pageurl, $cm = null) {
640 global $CFG, $COURSE;
516cf3eb 641
5bd22790 642 $this->contexts = $contexts;
643 $this->baseurl = $pageurl;
644 $this->cm = $cm;
645
646 if (!empty($cm) && $cm->modname == 'quiz') {
647 $this->quizorcourseid = '&amp;quizid=' . $cm->instance;
648 } else {
649 $this->quizorcourseid = '&amp;courseid=' .$COURSE->id;
650 }
651
652 // Create the url of the new question page to forward to.
653 $this->editquestionurl = new moodle_url("$CFG->wwwroot/question/question.php",
654 array('returnurl' => $pageurl->out()));
655 if ($cm !== null){
656 $this->editquestionurl->param('cmid', $cm->id);
657 } else {
658 $this->editquestionurl->param('courseid', $COURSE->id);
659 }
b221dc6f 660
661 $this->init_column_types();
662 $this->init_columns(array('checkbox', 'qtype', 'questionname', 'creatorname',
663 'modifiername', 'editaction', 'previewaction', 'moveaction', 'deleteaction'));
664 $this->init_sort();
665 }
666
babdcb40 667 protected function init_column_types() {
b221dc6f 668 $types = array(
669 new question_bank_checkbox_column($this),
670 new question_bank_question_type_column($this),
671 new question_bank_question_name_column($this),
672 new question_bank_creator_name_column($this),
673 new question_bank_modifier_name_column($this),
674 new question_bank_edit_action_column($this),
675 new question_bank_preview_action_column($this),
676 new question_bank_move_action_column($this),
677 new question_bank_delete_action_column($this),
678 );
679 $this->knowncolumntypes = array();
babdcb40 680 foreach ($types as $col) {
b221dc6f 681 $this->knowncolumntypes[$col->get_name()] = $col;
682 }
683 }
684
685 protected function init_columns($wanted) {
686 $this->visiblecolumns = array();
687 foreach ($wanted as $colname) {
688 if (!isset($this->knowncolumntypes[$colname])) {
689 throw new coding_exception('Unknown column type ' . $colname . ' requested in init columns.');
690 }
691 $this->visiblecolumns[$colname] = $this->knowncolumntypes[$colname];
692 }
693 $this->requiredcolumns = $this->visiblecolumns;
694 }
695
696 protected function init_sort() {
697 $this->init_sort_from_params();
698 if (empty($this->sort)) {
699 $this->sort = $this->default_sort();
700 }
701 }
702
703 /**
704 * Deal with a sort name of the forum columnname, or colname_subsort by
705 * breaking it up, validating the bits that are presend, and returning them.
706 * If there is no subsort, then $subsort is returned as ''.
707 * @return array array($colname, $subsort).
708 */
709 protected function parse_subsort($sort) {
710 /// Do the parsing.
711 if (strpos($sort, '_') !== false) {
712 list($colname, $subsort) = explode('_', $sort, 2);
713 } else {
714 $colname = $sort;
715 $subsort = '';
716 }
717 /// Validate the column name.
718 if (!isset($this->knowncolumntypes[$colname]) || !$this->knowncolumntypes[$colname]->is_sortable()) {
719 $this->baseurl->remove_params('qbs1', 'qbs2', 'qbs3');
720 throw new moodle_exception('unknownsortcolumn', '', $link = $this->baseurl->out(), $colname);
721 }
722 /// Validate the subsort, if present.
723 if ($subsort) {
724 $subsorts = $this->knowncolumntypes[$colname]->is_sortable();
725 if (!is_array($subsorts) || !isset($subsorts[$subsort])) {
726 throw new moodle_exception('unknownsortcolumn', '', $link = $this->baseurl->out(), $sort);
727 }
728 }
729 return array($colname, $subsort);
730 }
731
732 protected function init_sort_from_params() {
733 $this->sort = array();
734 for ($i = 1; $i < 3; $i++) {
735 if (!$sort = optional_param('qbs1', '', PARAM_ALPHAEXT)) {
736 break;
737 }
738 // Work out the appropriate order.
739 $order = 1;
740 if ($sort[0] == '-') {
741 $order = -1;
742 $sort = substr($sort1, 1);
743 if (!$sort) {
744 break;
745 }
746 }
747 // Deal with subsorts.
748 list($colname, $subsort) = $this->parse_subsort($sort);
749 $this->requiredcolumns[$colname] = $this->knowncolumntypes[$colname];
750 $sort[$sort] = $order;
751 }
752 }
753
754 protected function default_sort() {
755 return array('qtype' => 1, 'questionname' => 1);
756 }
757
758 protected function build_query_sql() {
759 /// Get the required tables.
760 $joins = array();
761 foreach ($this->requiredcolumns as $column) {
762 $extrajoins = $column->get_extra_joins();
763 foreach ($extrajoins as $prefix => $join) {
764 if (isset($joins[$prefix]) && $joins[$prefix] != $join) {
765 throw new coding_exception('Join ' . $join . ' conflicts with previous join ' . $joins[$prefix]);
766 }
767 $joins[$prefix] = $join;
768 }
769 }
770
771 /// Get the required fields.
772 $fields = array();
773 foreach ($this->visiblecolumns as $column) {
774 $fields += $column->get_required_fields();
775 }
776 $fields = array_unique($fields);
777
778 /// Build the order by clause.
779 $sorts = array();
780 foreach ($this->sort as $sort => $order) {
781 list($colname, $subsort) = $this->parse_subsort($sort);
782 $sorts[] = $this->knowncolumntypes[$colname]->sort_expression($order < 0, $subsort);
783 }
784
785 /// Build the SQL.
786 $sql = ' FROM {question} q ' . implode(' ', $joins);
787 // TODO where clause.
788 $sql .= ' ORDER BY ' . implode(', ', $sorts);
789 $this->countsql = 'SELECT count(1)' . $sql;
790 $this->loadsql = 'SELECT ' . implode(', ', $fields) . $sql;
5bd22790 791 }
792
793 public function base_url($questionid) {
794 return $baseurl;
795 }
796
797 public function edit_question_url($questionid) {
798 return $this->editquestionurl->out(false, array('id' => $questionid));
799 }
800
801 public function preview_question_url($questionid) {
802 global $CFG;
803 return $CFG->wwwroot . '/question/preview.php?id=' . $question->id . $this->quizorcourseid;
f4b879dd 804 }
516cf3eb 805
f4b879dd 806 /**
807 * Shows the question bank editing interface.
808 *
809 * The function also processes a number of actions:
810 *
811 * Actions affecting the question pool:
812 * move Moves a question to a different category
813 * deleteselected Deletes the selected questions from the category
814 * Other actions:
815 * category Chooses the category
816 * displayoptions Sets display options
f4b879dd 817 */
5bd22790 818 public function display($tabname, $page, $perpage, $sortorder,
f4b879dd 819 $sortorderdecoded, $cat, $recurse, $showhidden, $showquestiontext){
820 global $COURSE, $DB;
821
5bd22790 822 if ($this->process_actions_needing_ui()) {
5b5e5ab2 823 return;
f4b879dd 824 }
516cf3eb 825
5b5e5ab2 826 // Category selection form
f4b879dd 827 print_box_start('generalbox questionbank');
828 print_heading(get_string('questionbank', 'question'), '', 2);
5b5e5ab2 829
5bd22790 830 $this->display_category_form($this->contexts->having_one_edit_tab_cap($tabname),
831 $this->baseurl, $cat, $recurse, $showhidden, $showquestiontext);
624cbc9c 832
f4b879dd 833 // continues with list of questions
5bd22790 834 $this->display_question_list($this->contexts->having_one_edit_tab_cap($tabname), $this->baseurl, $cat, $this->cm,
f4b879dd 835 $recurse, $page, $perpage, $showhidden, $sortorder, $sortorderdecoded, $showquestiontext,
5bd22790 836 $this->contexts->having_cap('moodle/question:add'));
516cf3eb 837
f4b879dd 838 print_box_end();
516cf3eb 839 }
840
f4b879dd 841 /**
842 * prints a form to choose categories
843 */
5bd22790 844 protected function display_category_form($contexts, $pageurl, $current, $recurse=1,
5b5e5ab2 845 $showhidden=false, $showquestiontext=false) {
f4b879dd 846 global $CFG;
516cf3eb 847
f4b879dd 848 /// Get all the existing categories now
849 $catmenu = question_category_options($contexts, false, 0, true);
516cf3eb 850
f4b879dd 851 $strcategory = get_string('category', 'quiz');
852 $strshow = get_string('show', 'quiz');
853 $streditcats = get_string('editcategories', 'quiz');
854
5b5e5ab2 855 popup_form('edit.php?'.$pageurl->get_query_string().'&amp;category=',
856 $catmenu, 'catmenu', $current, '', '', '', false, 'self',
857 "<strong>$strcategory</strong>");
f4b879dd 858
859 echo '<form method="get" action="edit.php" id="displayoptions">';
860 echo "<fieldset class='invisiblefieldset'>";
861 echo $pageurl->hidden_params_out(array('recurse', 'showhidden', 'showquestiontext'));
862 $this->display_category_form_checkbox('recurse', $recurse);
863 $this->display_category_form_checkbox('showhidden', $showhidden);
864 $this->display_category_form_checkbox('showquestiontext', $showquestiontext);
865 echo '<noscript><div class="centerpara"><input type="submit" value="'. get_string('go') .'" />';
866 echo '</div></noscript></fieldset></form>';
516cf3eb 867 }
868
f4b879dd 869 /**
870 * Private funciton to help the preceeding function.
871 */
872 protected function display_category_form_checkbox($name, $checked) {
873 echo '<div><input type="hidden" id="' . $name . '_off" name="' . $name . '" value="0" />';
874 echo '<input type="checkbox" id="' . $name . '_on" name="' . $name . '" value="1"';
875 if ($checked) {
876 echo ' checked="checked"';
516cf3eb 877 }
f4b879dd 878 echo ' onchange="getElementById(\'displayoptions\').submit(); return true;" />';
879 echo '<label for="' . $name . '_on">';
880 print_string($name, 'quiz');
881 echo "</label></div>\n";
516cf3eb 882 }
883
f4b879dd 884 /**
885 * Prints the table of questions in a category with interactions
886 *
887 * @param object $course The course object
888 * @param int $categoryid The id of the question category to be displayed
889 * @param int $cm The course module record if we are in the context of a particular module, 0 otherwise
890 * @param int $recurse This is 1 if subcategories should be included, 0 otherwise
891 * @param int $page The number of the page to be displayed
892 * @param int $perpage Number of questions to show per page
893 * @param boolean $showhidden True if also hidden questions should be displayed
894 * @param boolean $showquestiontext whether the text of each question should be shown in the list
895 */
5bd22790 896 protected function display_question_list($contexts, $pageurl, $categoryandcontext,
5b5e5ab2 897 $cm = null, $recurse=1, $page=0, $perpage=100, $showhidden=false,
898 $sortorder='typename', $sortorderdecoded='qtype, name ASC',
f4b879dd 899 $showquestiontext = false, $addcontexts = array()) {
5bd22790 900 global $CFG, $COURSE, $DB;
f4b879dd 901
902 list($categoryid, $contextid)= explode(',', $categoryandcontext);
903
904 $qtypemenu = question_type_menu();
905
906 $strcategory = get_string("category", "quiz");
907 $strquestion = get_string("question", "quiz");
908 $straddquestions = get_string("addquestions", "quiz");
909 $strimportquestions = get_string("importquestions", "quiz");
910 $strexportquestions = get_string("exportquestions", "quiz");
5b5e5ab2 911 $strnoquestions = get_string("noquestions", "quiz");
f4b879dd 912 $strselect = get_string("select", "quiz");
913 $strselectall = get_string("selectall", "quiz");
914 $strselectnone = get_string("selectnone", "quiz");
915 $strcreatenewquestion = get_string("createnewquestion", "quiz");
5b5e5ab2 916 $strquestion = get_string("question", "quiz");
f4b879dd 917 $strdelete = get_string("delete");
918 $stredit = get_string("edit");
919 $strmove = get_string('moveqtoanothercontext', 'question');
920 $strview = get_string("view");
921 $straction = get_string("action");
922 $strrestore = get_string('restore');
923
924 $strtype = get_string("type", "quiz");
925 $strcreatemultiple = get_string("createmultiple", "quiz");
926 $strpreview = get_string("preview","quiz");
927
928 if (!$categoryid) {
929 echo "<p style=\"text-align:center;\"><b>";
930 print_string("selectcategoryabove", "quiz");
931 echo "</b></p>";
932 return;
624cbc9c 933 }
f4b879dd 934
5b5e5ab2 935 if (!$category = $DB->get_record('question_categories',
936 array('id' => $categoryid, 'contextid' => $contextid))) {
f4b879dd 937 notify('Category not found!');
938 return;
624cbc9c 939 }
5b5e5ab2 940
f4b879dd 941 $catcontext = get_context_instance_by_id($contextid);
942 $canadd = has_capability('moodle/question:add', $catcontext);
943 //check for capabilities on all questions in category, will also apply to sub cats.
944 $caneditall =has_capability('moodle/question:editall', $catcontext);
945 $canuseall =has_capability('moodle/question:useall', $catcontext);
946 $canmoveall =has_capability('moodle/question:moveall', $catcontext);
947
948 if ($cm AND $cm->modname == 'quiz') {
949 $quizid = $cm->instance;
950 } else {
951 $quizid = 0;
624cbc9c 952 }
5b5e5ab2 953
954 // Create the url of the new question page to forward to.
f4b879dd 955 $returnurl = $pageurl->out();
956 $questionurl = new moodle_url("$CFG->wwwroot/question/question.php",
957 array('returnurl' => $returnurl));
958 if ($cm!==null){
959 $questionurl->param('cmid', $cm->id);
960 } else {
961 $questionurl->param('courseid', $COURSE->id);
624cbc9c 962 }
f4b879dd 963 $questionmoveurl = new moodle_url("$CFG->wwwroot/question/contextmoveq.php",
964 array('returnurl' => $returnurl));
965 if ($cm!==null){
966 $questionmoveurl->param('cmid', $cm->id);
967 } else {
968 $questionmoveurl->param('courseid', $COURSE->id);
516cf3eb 969 }
5b5e5ab2 970
f4b879dd 971 echo '<div class="boxaligncenter">';
972 $formatoptions = new stdClass;
973 $formatoptions->noclean = true;
974 echo format_text($category->info, FORMAT_MOODLE, $formatoptions, $COURSE->id);
5b5e5ab2 975 echo "</div>\n";
f4b879dd 976
5b5e5ab2 977 echo '<div class="createnewquestion">';
f4b879dd 978 if ($canadd) {
5b5e5ab2 979 popup_form($questionurl->out(false, array('category' => $category->id)).
980 '&amp;qtype=', $qtypemenu, "addquestion", "", "choose", "",
981 "", false, "self", "<strong>$strcreatenewquestion</strong>");
f4b879dd 982 helpbutton("questiontypes", $strcreatenewquestion, "quiz");
5b5e5ab2 983 } else {
f4b879dd 984 print_string('nopermissionadd', 'question');
271e6dec 985 }
f4b879dd 986 echo '</div>';
987
988 $categorylist = ($recurse) ? question_categorylist($category->id) : $category->id;
5b5e5ab2 989 $categorylist_array = explode(',', $categorylist);
f4b879dd 990
f4b879dd 991 $showhidden = $showhidden ? '' : " AND hidden = '0'";
5b5e5ab2 992
f4b879dd 993 list($usql, $params) = $DB->get_in_or_equal($categorylist_array);
5b5e5ab2 994 if (!$totalnumber = $DB->count_records_select('question',
995 "category $usql AND parent = '0' $showhidden", $params)) {
996 echo '<div class="categoryquestionscontainer noquestionsincategory">';
997 print_string('noquestions', 'quiz');
998 echo '</div>';
f4b879dd 999 return;
271e6dec 1000 }
1001
5b5e5ab2 1002 if (!$questions = $DB->get_records_select('question',
1003 "category $usql AND parent = '0' $showhidden", $params, $sortorderdecoded,
1004 '*', $page*$perpage, $perpage)) {
1005
f4b879dd 1006 // There are no questions on the requested page.
1007 $page = 0;
5b5e5ab2 1008 if (!$questions = $DB->get_records_select('question',
1009 "category $usql AND parent = '0' $showhidden", $params, $sortorderdecoded,
1010 '*', 0, $perpage)) {
f4b879dd 1011 // There are no questions at all
5b5e5ab2 1012 echo '<div class="categoryquestionscontainer noquestionsincategory">';
1013 print_string('noquestions', 'quiz');
1014 echo '</div>';
f4b879dd 1015 return;
516cf3eb 1016 }
1017 }
516cf3eb 1018
5b5e5ab2 1019 echo '<div class="categorysortopotionscontainer">';
f4b879dd 1020 $this->display_question_sort_options($pageurl, $sortorder);
5b5e5ab2 1021 echo '</div>';
1022
1023 echo '<div class="categorypagingbarcontainer">';
1024 print_paging_bar($totalnumber, $page, $perpage, $pageurl, 'qpage');
1025 echo '</div>';
f4b879dd 1026
1027 echo '<form method="post" action="edit.php">';
1028 echo '<fieldset class="invisiblefieldset" style="display: block;">';
1029 echo '<input type="hidden" name="sesskey" value="'.sesskey().'" />';
1030 echo $pageurl->hidden_params_out();
5b5e5ab2 1031 echo '<div class="categoryquestionscontainer">';
1032 echo '<table id="categoryquestions" style="width: 100%"><colgroup><col id="qaction"></col><col id="qname"></col><col id="qextraactions"></col></colgroup><tr>';
f4b879dd 1033 echo "<th style=\"white-space:nowrap;\" class=\"header\" scope=\"col\">$straction</th>";
1034
5b5e5ab2 1035 echo "<th style=\"white-space:nowrap; text-align: left;\" class=\"header\" scope=\"col\">$strquestion</th>";
1036 echo "<th style=\"white-space:nowrap; text-align: left;\" class=\"header\" scope=\"col\"></th>";
516cf3eb 1037 echo "</tr>\n";
f4b879dd 1038 foreach ($questions as $question) {
1039 $nameclass = '';
1040 $textclass = '';
1041 if ($question->hidden) {
1042 $nameclass = 'dimmed_text';
1043 $textclass = 'dimmed_text';
1044 }
1045 if ($showquestiontext) {
1046 $nameclass .= ' header';
1047 }
1048 if ($nameclass) {
1049 $nameclass = 'class="' . $nameclass . '"';
1050 }
1051 if ($textclass) {
1052 $textclass = 'class="' . $textclass . '"';
1053 }
624cbc9c 1054
f4b879dd 1055 echo "<tr>\n<td style=\"white-space:nowrap;\" $nameclass>\n";
516cf3eb 1056
f4b879dd 1057 $canuseq = question_has_capability_on($question, 'use', $question->category);
1058 if (function_exists('module_specific_actions')) {
1059 echo module_specific_actions($pageurl, $question->id, $cm->id, $canuseq);
1060 }
95947ac9 1061
5b5e5ab2 1062 if ($caneditall || $canmoveall || $canuseall){
1063 echo "<input title=\"$strselect\" type=\"checkbox\" name=\"q$question->id\" id=\"checkq$question->id\" value=\"1\" />";
1064 }
1065 echo "</td>\n";
1066
1067 echo "<td $nameclass><div>";
1068 print_question_icon($question);
1069 echo format_string($question->name);
1070 echo "</div></td>\n";
1071
1072 echo "<td>\n";
1073
1074 // edit, hide, delete question, using question capabilities, not quiz capabilities
1075 if (question_has_capability_on($question, 'edit', $question->category) ||
1076 question_has_capability_on($question, 'move', $question->category)) {
1077 echo "<a title=\"$stredit\" href=\"".$questionurl->out(false, array('id'=>$question->id))."\">
1078 <img src=\"$CFG->pixpath/t/edit.gif\" alt=\"$stredit\" /></a>";
1079 } elseif (question_has_capability_on($question, 'view', $question->category)) {
1080 echo "<a title=\"$strview\" href=\"".$questionurl->out(false, array('id'=>$question->id))."\">
1081 <img src=\"$CFG->pixpath/i/info.gif\" alt=\"$strview\" /></a>";
1082 }
1083
f4b879dd 1084 // preview
1085 if ($canuseq) {
1086 $quizorcourseid = $quizid?('&amp;quizid=' . $quizid):('&amp;courseid=' .$COURSE->id);
5b5e5ab2 1087 link_to_popup_window('/question/preview.php?id=' . $question->id .
1088 $quizorcourseid, 'questionpreview',
1089 " <img src=\"$CFG->pixpath/t/preview.gif\" class=\"iconsmall\" alt=\"$strpreview\" />",
f4b879dd 1090 0, 0, $strpreview, QUESTION_PREVIEW_POPUP_OPTIONS);
1091 }
f4b879dd 1092
1093 if (question_has_capability_on($question, 'move', $question->category) && question_has_capability_on($question, 'view', $question->category)) {
5b5e5ab2 1094 echo "<a title=\"$strmove\" href=\"".$questionurl->out(false, array('id'=>$question->id, 'movecontext'=>1))."\">
1095 <img src=\"$CFG->pixpath/t/move.gif\" alt=\"$strmove\" /></a>";
f4b879dd 1096 }
516cf3eb 1097
f4b879dd 1098 if (question_has_capability_on($question, 'edit', $question->category)) {
1099 // hide-feature
1100 if($question->hidden) {
5b5e5ab2 1101 echo "<a title=\"$strrestore\" href=\"edit.php?".$pageurl->get_query_string()."&amp;unhide=$question->id&amp;sesskey=".sesskey()."\">
1102 <img src=\"$CFG->pixpath/t/restore.gif\" alt=\"$strrestore\" /></a>";
f4b879dd 1103 } else {
5b5e5ab2 1104 echo "<a title=\"$strdelete\" href=\"edit.php?".$pageurl->get_query_string()."&amp;deleteselected=$question->id&amp;q$question->id=1\">
1105 <img src=\"$CFG->pixpath/t/delete.gif\" alt=\"$strdelete\" /></a>";
f4b879dd 1106 }
1107 }
f4b879dd 1108 echo "</td>\n";
1109
f4b879dd 1110 echo "</tr>\n";
1111 if($showquestiontext){
1112 echo '<tr><td colspan="3" ' . $textclass . '>';
1113 $formatoptions = new stdClass;
1114 $formatoptions->noclean = true;
1115 $formatoptions->para = false;
1116 echo format_text($question->questiontext, $question->questiontextformat,
1117 $formatoptions, $COURSE->id);
1118 echo "</td></tr>\n";
1119 }
271e6dec 1120 }
5b5e5ab2 1121 echo "</table></div>\n";
86909ce0 1122
5b5e5ab2 1123 echo '<div class="categorypagingbarcontainer pagingbottom">';
f4b879dd 1124 $paging = print_paging_bar($totalnumber, $page, $perpage, $pageurl, 'qpage', false, true);
1125 if ($totalnumber > DEFAULT_QUESTIONS_PER_PAGE) {
1126 if ($perpage == DEFAULT_QUESTIONS_PER_PAGE) {
1127 $showall = '<a href="edit.php?'.$pageurl->get_query_string(array('qperpage'=>1000)).'">'.get_string('showall', 'moodle', $totalnumber).'</a>';
1128 } else {
1129 $showall = '<a href="edit.php?'.$pageurl->get_query_string(array('qperpage'=>DEFAULT_QUESTIONS_PER_PAGE)).'">'.get_string('showperpage', 'moodle', DEFAULT_QUESTIONS_PER_PAGE).'</a>';
1130 }
1131 if ($paging) {
1132 $paging = substr($paging, 0, strrpos($paging, '</div>'));
1133 $paging .= "<br />$showall</div>";
1134 } else {
1135 $paging = "<div class='paging'>$showall</div>";
1136 }
86909ce0 1137 }
f4b879dd 1138 echo $paging;
5b5e5ab2 1139 echo '</div>';
f4b879dd 1140
5b5e5ab2 1141 echo '<div class="categoryselectallcontainer">';
f4b879dd 1142 if ($caneditall || $canmoveall || $canuseall){
1143 echo '<a href="javascript:select_all_in(\'TABLE\',null,\'categoryquestions\');">'.$strselectall.'</a> /'.
1144 ' <a href="javascript:deselect_all_in(\'TABLE\',null,\'categoryquestions\');">'.$strselectnone.'</a>';
1145 echo '<br />';
5b5e5ab2 1146 }
1147 echo "</div>\n";
1148
1149 echo '<div class="modulespecificbuttonscontainer">';
1150 if ($caneditall || $canmoveall || $canuseall){
f4b879dd 1151 echo '<strong>&nbsp;'.get_string('withselected', 'quiz').':</strong><br />';
1152
1153 if (function_exists('module_specific_buttons')) {
1154 echo module_specific_buttons($cm->id);
1155 }
5b5e5ab2 1156
f4b879dd 1157 // print delete and move selected question
1158 if ($caneditall) {
5b5e5ab2 1159 echo '<input type="submit" name="deleteselected" value="' . $strdelete . "\" />\n";
f4b879dd 1160 }
5b5e5ab2 1161
f4b879dd 1162 if ($canmoveall && count($addcontexts)) {
1163 echo '<input type="submit" name="move" value="'.get_string('moveto', 'quiz')."\" />\n";
1164 question_category_select_menu($addcontexts, false, 0, "$category->id,$category->contextid");
1165 }
1166
1167 if (function_exists('module_specific_controls') && $canuseall) {
5b5e5ab2 1168 $modulespecific = module_specific_controls($totalnumber, $recurse, $category, $cm->id);
1169 if(!empty($modulespecific)){
1170 echo "<hr />$modulespecific";
1171 }
271e6dec 1172 }
1173 }
5b5e5ab2 1174 echo "</div>\n";
1175
f4b879dd 1176 echo '</fieldset>';
1177 echo "</form>\n";
1178 }
1179
5bd22790 1180 protected function display_question_sort_options($pageurl, $sortorder){
f4b879dd 1181 //sort options
1182 $html = "<div class=\"mdl-align questionsortoptions\">";
1183 // POST method should only be used for parameters that change data
1184 // or if POST method has to be used, the user must be redirected immediately to
1185 // non-POSTed page to not break the back button
1186 $html .= '<form method="get" action="edit.php">';
1187 $html .= '<fieldset class="invisiblefieldset" style="display: block;">';
1188 $html .= '<input type="hidden" name="sesskey" value="'.sesskey().'" />';
1189 $html .= $pageurl->hidden_params_out(array('qsortorder'));
1190 //choose_from_menu concatenates the form name with
1191 //"menu" so the label is for menuqsortorder
1192 $sortoptions = array('alpha' => get_string("qname", "quiz"),
1193 'typealpha' => get_string("qtypename", "quiz"),
1194 'age' => get_string("age", "quiz"));
1195 $a = choose_from_menu($sortoptions, 'qsortorder', $sortorder, false, 'this.form.submit();', '0', true);
1196 $html .= '<label for="menuqsortorder">'.get_string('sortquestionsbyx', 'quiz', $a).'</label>';
1197 $html .= '<noscript><div><input type="submit" value="'.get_string("sortsubmit", "quiz").'" /></div></noscript>';
1198 $html .= '</fieldset>';
1199 $html .= "</form>\n";
1200 $html .= "</div>\n";
1201 echo $html;
1202 }
1203
5bd22790 1204 public function process_actions() {
f4b879dd 1205 global $CFG, $COURSE, $DB;
1206 /// Now, check for commands on this page and modify variables as necessary
1207 if (optional_param('move', false, PARAM_BOOL) and confirm_sesskey()) { /// Move selected questions to new category
1208 $category = required_param('category', PARAM_SEQUENCE);
1209 list($tocategoryid, $contextid) = explode(',', $category);
1210 if (! $tocategory = $DB->get_record('question_categories', array('id' => $tocategoryid, 'contextid' => $contextid))) {
1211 print_error('cannotfindcate', 'question');
271e6dec 1212 }
f4b879dd 1213 $tocontext = get_context_instance_by_id($contextid);
1214 require_capability('moodle/question:add', $tocontext);
1215 $rawdata = (array) data_submitted();
1216 $questionids = array();
1217 foreach ($rawdata as $key => $value) { // Parse input for question ids
1218 if (preg_match('!^q([0-9]+)$!', $key, $matches)) {
1219 $key = $matches[1];
1220 $questionids[] = $key;
271e6dec 1221 }
1222 }
f4b879dd 1223 if ($questionids){
1224 list($usql, $params) = $DB->get_in_or_equal($questionids);
1225 $sql = "SELECT q.*, c.contextid FROM {question} q, {question_categories} c WHERE q.id $usql AND c.id = q.category";
1226 if (!$questions = $DB->get_records_sql($sql, $params)){
1227 print_error('questiondoesnotexist', 'question', $pageurl->out());
271e6dec 1228 }
f4b879dd 1229 $checkforfiles = false;
1230 foreach ($questions as $question){
1231 //check capabilities
1232 question_require_capability_on($question, 'move');
1233 $fromcontext = get_context_instance_by_id($question->contextid);
1234 if (get_filesdir_from_context($fromcontext) != get_filesdir_from_context($tocontext)){
1235 $checkforfiles = true;
1236 }
1237 }
1238 $returnurl = $pageurl->out(false, array('category'=>"$tocategoryid,$contextid"));
1239 if (!$checkforfiles){
1240 if (!question_move_questions_to_category(implode(',', $questionids), $tocategory->id)) {
1241 print_error('errormovingquestions', 'question', $returnurl, $questionids);
1242 }
1243 redirect($returnurl);
271e6dec 1244 } else {
f4b879dd 1245 $movecontexturl = new moodle_url($CFG->wwwroot.'/question/contextmoveq.php',
1246 array('returnurl' => $returnurl,
1247 'ids'=>$questionidlist,
1248 'tocatid'=> $tocategoryid));
1249 if ($cm){
1250 $movecontexturl->param('cmid', $cm->id);
1251 } else {
1252 $movecontexturl->param('courseid', $COURSE->id);
1253 }
1254 redirect($movecontexturl->out());
86909ce0 1255 }
1256 }
1257 }
86909ce0 1258
f4b879dd 1259 if (optional_param('deleteselected', false, PARAM_BOOL)) { // delete selected questions from the category
1260 if (($confirm = optional_param('confirm', '', PARAM_ALPHANUM)) and confirm_sesskey()) { // teacher has already confirmed the action
1261 $deleteselected = required_param('deleteselected');
1262 if ($confirm == md5($deleteselected)) {
1263 if ($questionlist = explode(',', $deleteselected)) {
1264 // for each question either hide it if it is in use or delete it
1265 foreach ($questionlist as $questionid) {
1266 question_require_capability_on($questionid, 'edit');
1267 if ($DB->record_exists('quiz_question_instances', array('question' => $questionid))) {
1268 if (!$DB->set_field('question', 'hidden', 1, array('id' => $questionid))) {
1269 question_require_capability_on($questionid, 'edit');
1270 print_error('cannothidequestion', 'question');
1271 }
1272 } else {
1273 delete_question($questionid);
86909ce0 1274 }
86909ce0 1275 }
1276 }
f4b879dd 1277 redirect($pageurl->out());
1278 } else {
1279 print_error('invalidconfirm', 'question');
86909ce0 1280 }
86909ce0 1281 }
86909ce0 1282 }
8e77884c 1283
f4b879dd 1284 // Unhide a question
1285 if(($unhide = optional_param('unhide', '', PARAM_INT)) and confirm_sesskey()) {
1286 question_require_capability_on($unhide, 'edit');
1287 if(!$DB->set_field('question', 'hidden', 0, array('id', $unhide))) {
1288 print_error('cannotunhidequestion', 'question');
271e6dec 1289 }
271e6dec 1290 redirect($pageurl->out());
1291 }
271e6dec 1292 }
5bd22790 1293
1294 public function process_actions_needing_ui() {
1295 if (optional_param('deleteselected', false, PARAM_BOOL)) {
1296 // make a list of all the questions that are selected
1297 $rawquestions = $_REQUEST; // This code is called by both POST forms and GET links, so cannot use data_submitted.
1298 $questionlist = ''; // comma separated list of ids of questions to be deleted
1299 $questionnames = ''; // string with names of questions separated by <br /> with
1300 // an asterix in front of those that are in use
1301 $inuse = false; // set to true if at least one of the questions is in use
1302 foreach ($rawquestions as $key => $value) { // Parse input for question ids
1303 if (preg_match('!^q([0-9]+)$!', $key, $matches)) {
1304 $key = $matches[1];
1305 $questionlist .= $key.',';
1306 question_require_capability_on($key, 'edit');
1307 if ($DB->record_exists('quiz_question_instances', array('question' => $key))) {
1308 $questionnames .= '* ';
1309 $inuse = true;
1310 }
1311 $questionnames .= $DB->get_field('question', 'name', array('id' => $key)) . '<br />';
1312 }
1313 }
1314 if (!$questionlist) { // no questions were selected
1315 redirect($this->baseurl->out());
1316 }
1317 $questionlist = rtrim($questionlist, ',');
1318
1319 // Add an explanation about questions in use
1320 if ($inuse) {
1321 $questionnames .= '<br />'.get_string('questionsinuse', 'quiz');
1322 }
1323 notice_yesno(get_string("deletequestionscheck", "quiz", $questionnames),
1324 $pageurl->out_action(array('deleteselected'=>$questionlist, 'confirm'=>md5($questionlist))),
1325 $pageurl->out_action());
1326
1327 return true;
1328 }
1329 }
86909ce0 1330}
f4b879dd 1331
b72ff476 1332/**
1333 * Common setup for all pages for editing questions.
271e6dec 1334 * @param string $edittab code for this edit tab
b72ff476 1335 * @param boolean $requirecmid require cmid? default false
1336 * @param boolean $requirecourseid require courseid, if cmid is not given? default true
271e6dec 1337 * @return array $thispageurl, $contexts, $cmid, $cm, $module, $pagevars
b72ff476 1338 */
271e6dec 1339function question_edit_setup($edittab, $requirecmid = false, $requirecourseid = true){
f34488b2 1340 global $COURSE, $QUESTION_EDITTABCAPS, $DB;
271e6dec 1341
1342 //$thispageurl is used to construct urls for all question edit pages we link to from this page. It contains an array
36e298bc 1343 //of parameters that are passed from page to page.
b72ff476 1344 $thispageurl = new moodle_url();
b4a2e413 1345 $thispageurl->remove_params(); // We are going to explicity add back everything important - this avoids unwanted params from being retained.
1346
b72ff476 1347 if ($requirecmid){
1348 $cmid =required_param('cmid', PARAM_INT);
1349 } else {
1350 $cmid = optional_param('cmid', 0, PARAM_INT);
1351 }
1352 if ($cmid){
271e6dec 1353 list($module, $cm) = get_module_from_cmid($cmid);
b72ff476 1354 $courseid = $cm->course;
1355 $thispageurl->params(compact('cmid'));
271e6dec 1356 require_login($courseid, false, $cm);
1357 $thiscontext = get_context_instance(CONTEXT_MODULE, $cmid);
b72ff476 1358 } else {
1359 $module = null;
1360 $cm = null;
1361 if ($requirecourseid){
1362 $courseid = required_param('courseid', PARAM_INT);
1363 } else {
1364 $courseid = optional_param('courseid', 0, PARAM_INT);
1365 }
1366 if ($courseid){
1367 $thispageurl->params(compact('courseid'));
271e6dec 1368 require_login($courseid, false);
1369 $thiscontext = get_context_instance(CONTEXT_COURSE, $courseid);
1370 } else {
1371 $thiscontext = null;
b72ff476 1372 }
1373 }
271e6dec 1374
1375 if ($thiscontext){
1376 $contexts = new question_edit_contexts($thiscontext);
1377 $contexts->require_one_edit_tab_cap($edittab);
1378
1379 } else {
1380 $contexts = null;
1381 }
1382
1383
1384
36e298bc 1385 $pagevars['qpage'] = optional_param('qpage', -1, PARAM_INT);
271e6dec 1386
7bc26c8f 1387 //pass 'cat' from page to page and when 'category' comes from a drop down menu
271e6dec 1388 //then we also reset the qpage so we go to page 1 of
7bc26c8f 1389 //a new cat.
271e6dec 1390 $pagevars['cat'] = optional_param('cat', 0, PARAM_SEQUENCE);// if empty will be set up later
1391 if ($category = optional_param('category', 0, PARAM_SEQUENCE)){
a18fbcfb 1392 if ($pagevars['cat'] != $category){ // is this a move to a new category?
1393 $pagevars['cat'] = $category;
1394 $pagevars['qpage'] = 0;
1395 }
7bc26c8f 1396 }
1397 if ($pagevars['cat']){
1398 $thispageurl->param('cat', $pagevars['cat']);
1399 }
b72ff476 1400 if ($pagevars['qpage'] > -1) {
1401 $thispageurl->param('qpage', $pagevars['qpage']);
1402 } else {
1403 $pagevars['qpage'] = 0;
1404 }
1405
36e298bc 1406 $pagevars['qperpage'] = optional_param('qperpage', -1, PARAM_INT);
b72ff476 1407 if ($pagevars['qperpage'] > -1) {
1408 $thispageurl->param('qperpage', $pagevars['qperpage']);
1409 } else {
1410 $pagevars['qperpage'] = DEFAULT_QUESTIONS_PER_PAGE;
1411 }
271e6dec 1412
36e298bc 1413 $sortoptions = array('alpha' => 'name, qtype ASC',
1414 'typealpha' => 'qtype, name ASC',
1415 'age' => 'id ASC');
1416
1417 if ($sortorder = optional_param('qsortorder', '', PARAM_ALPHA)) {
1418 $pagevars['qsortorderdecoded'] = $sortoptions[$sortorder];
1419 $pagevars['qsortorder'] = $sortorder;
1420 $thispageurl->param('qsortorder', $sortorder);
b72ff476 1421 } else {
7bc26c8f 1422 $pagevars['qsortorderdecoded'] = $sortoptions['typealpha'];
1423 $pagevars['qsortorder'] = 'typealpha';
271e6dec 1424 }
36e298bc 1425
271e6dec 1426 $defaultcategory = question_make_default_categories($contexts->all());
1427
1428 $contextlistarr = array();
1429 foreach ($contexts->having_one_edit_tab_cap($edittab) as $context){
1430 $contextlistarr[] = "'$context->id'";
1431 }
1432 $contextlist = join($contextlistarr, ' ,');
1433 if (!empty($pagevars['cat'])){
1434 $catparts = explode(',', $pagevars['cat']);
f34488b2 1435 if (!$catparts[0] || (FALSE !== array_search($catparts[1], $contextlistarr)) ||
1436 !$DB->count_records_select("question_categories", "id = ? AND contextid = ?", array($catparts[0], $catparts[1]))) {
5a2a5331 1437 print_error('invalidcategory', 'quiz');
271e6dec 1438 }
1439 } else {
1440 $category = $defaultcategory;
1441 $pagevars['cat'] = "$category->id,$category->contextid";
36e298bc 1442 }
1443
1444 if(($recurse = optional_param('recurse', -1, PARAM_BOOL)) != -1) {
1445 $pagevars['recurse'] = $recurse;
1446 $thispageurl->param('recurse', $recurse);
1447 } else {
1448 $pagevars['recurse'] = 1;
1449 }
271e6dec 1450
36e298bc 1451 if(($showhidden = optional_param('showhidden', -1, PARAM_BOOL)) != -1) {
1452 $pagevars['showhidden'] = $showhidden;
1453 $thispageurl->param('showhidden', $showhidden);
1454 } else {
1455 $pagevars['showhidden'] = 0;
1456 }
271e6dec 1457
36e298bc 1458 if(($showquestiontext = optional_param('showquestiontext', -1, PARAM_BOOL)) != -1) {
1459 $pagevars['showquestiontext'] = $showquestiontext;
1460 $thispageurl->param('showquestiontext', $showquestiontext);
1461 } else {
1462 $pagevars['showquestiontext'] = 0;
1463 }
271e6dec 1464
986effb6 1465 //category list page
1466 $pagevars['cpage'] = optional_param('cpage', 1, PARAM_INT);
1467 if ($pagevars['cpage'] != 1){
1468 $thispageurl->param('cpage', $pagevars['cpage']);
1469 }
36e298bc 1470
271e6dec 1471
1472 return array($thispageurl, $contexts, $cmid, $cm, $module, $pagevars);
1473}
1474class question_edit_contexts{
1475 var $allcontexts;
1476 /**
1477 * @param current context
1478 */
1479 function question_edit_contexts($thiscontext){
1480 $pcontextids = get_parent_contexts($thiscontext);
1481 $contexts = array($thiscontext);
1482 foreach ($pcontextids as $pcontextid){
1483 $contexts[] = get_context_instance_by_id($pcontextid);
1484 }
1485 $this->allcontexts = $contexts;
1486 }
1487 /**
1488 * @return array all parent contexts
1489 */
1490 function all(){
1491 return $this->allcontexts;
1492 }
1493 /**
1494 * @return object lowest context which must be either the module or course context
1495 */
1496 function lowest(){
1497 return $this->allcontexts[0];
1498 }
1499 /**
1500 * @param string $cap capability
1501 * @return array parent contexts having capability, zero based index
1502 */
1503 function having_cap($cap){
1504 $contextswithcap = array();
1505 foreach ($this->allcontexts as $context){
1506 if (has_capability($cap, $context)){
1507 $contextswithcap[] = $context;
1508 }
1509 }
1510 return $contextswithcap;
1511 }
1512 /**
1513 * @param array $caps capabilities
1514 * @return array parent contexts having at least one of $caps, zero based index
1515 */
1516 function having_one_cap($caps){
1517 $contextswithacap = array();
1518 foreach ($this->allcontexts as $context){
1519 foreach ($caps as $cap){
1520 if (has_capability($cap, $context)){
1521 $contextswithacap[] = $context;
1522 break; //done with caps loop
1523 }
1524 }
1525 }
1526 return $contextswithacap;
1527 }
1528 /**
1529 * @param string $tabname edit tab name
1530 * @return array parent contexts having at least one of $caps, zero based index
1531 */
1532 function having_one_edit_tab_cap($tabname){
1533 global $QUESTION_EDITTABCAPS;
1534 return $this->having_one_cap($QUESTION_EDITTABCAPS[$tabname]);
1535 }
1536 /**
1537 * Has at least one parent context got the cap $cap?
1538 *
1539 * @param string $cap capability
1540 * @return boolean
1541 */
1542 function have_cap($cap){
1543 return (count($this->having_cap($cap)));
1544 }
1545
1546 /**
1547 * Has at least one parent context got one of the caps $caps?
1548 *
1549 * @param string $cap capability
1550 * @return boolean
1551 */
1552 function have_one_cap($caps){
1553 foreach ($caps as $cap){
1554 if ($this->have_cap($cap)){
1555 return true;
1556 }
1557 }
1558 return false;
1559 }
1560 /**
1561 * Has at least one parent context got one of the caps for actions on $tabname
1562 *
1563 * @param string $tabname edit tab name
1564 * @return boolean
1565 */
1566 function have_one_edit_tab_cap($tabname){
1567 global $QUESTION_EDITTABCAPS;
1568 return $this->have_one_cap($QUESTION_EDITTABCAPS[$tabname]);
1569 }
1570 /**
1571 * Throw error if at least one parent context hasn't got the cap $cap
1572 *
1573 * @param string $cap capability
1574 */
1575 function require_cap($cap){
1576 if (!$this->have_cap($cap)){
1577 print_error('nopermissions', '', '', $cap);
1578 }
1579 }
1580 /**
1581 * Throw error if at least one parent context hasn't got one of the caps $caps
1582 *
1583 * @param array $cap capabilities
1584 */
1585 function require_one_cap($caps){
1586 if (!$this->have_one_cap($caps)){
1587 $capsstring = join($caps, ', ');
1588 print_error('nopermissions', '', '', $capsstring);
1589 }
1590 }
1591 /**
1592 * Throw error if at least one parent context hasn't got one of the caps $caps
1593 *
1594 * @param string $tabname edit tab name
1595 */
1596 function require_one_edit_tab_cap($tabname){
1597 if (!$this->have_one_edit_tab_cap($tabname)){
1598 print_error('nopermissions', '', '', 'access question edit tab '.$tabname);
1599 }
1600 }
1601}
1602
1603//capabilities for each page of edit tab.
1604//this determines which contexts' categories are available. At least one
1605//page is displayed if user has one of the capability on at least one context
1606$QUESTION_EDITTABCAPS = array(
a856c14e 1607 'editq' => array('moodle/question:add',
1608 'moodle/question:editmine',
1609 'moodle/question:editall',
1610 'moodle/question:viewmine',
1611 'moodle/question:viewall',
1612 'moodle/question:usemine',
1613 'moodle/question:useall',
1614 'moodle/question:movemine',
1615 'moodle/question:moveall'),
1616 'questions'=>array('moodle/question:add',
1617 'moodle/question:editmine',
1618 'moodle/question:editall',
1619 'moodle/question:viewmine',
1620 'moodle/question:viewall',
1621 'moodle/question:movemine',
1622 'moodle/question:moveall'),
1623 'categories'=>array('moodle/question:managecategory'),
1624 'import'=>array('moodle/question:add'),
1625 'export'=>array('moodle/question:viewall', 'moodle/question:viewmine'));
271e6dec 1626
1627/**
1628 * Make sure user is logged in as required in this context.
1629 */
1630function require_login_in_context($contextorid = null){
f34488b2 1631 global $DB;
271e6dec 1632 if (!is_object($contextorid)){
1633 $context = get_context_instance_by_id($contextorid);
1634 } else {
1635 $context = $contextorid;
1636 }
1637 if ($context && ($context->contextlevel == CONTEXT_COURSE)) {
1638 require_login($context->instanceid);
1639 } else if ($context && ($context->contextlevel == CONTEXT_MODULE)) {
f34488b2 1640 if ($cm = $DB->get_record('course_modules',array('id' =>$context->instanceid))) {
1641 if (!$course = $DB->get_record('course', array('id' => $cm->course))) {
0be2c858 1642 print_error('invalidcourseid');
271e6dec 1643 }
1644 require_course_login($course, true, $cm);
1645
1646 } else {
0be2c858 1647 print_error('invalidcoursemodule');
271e6dec 1648 }
1649 } else if ($context && ($context->contextlevel == CONTEXT_SYSTEM)) {
1650 if (!empty($CFG->forcelogin)) {
1651 require_login();
1652 }
1653
1654 } else {
1655 require_login();
1656 }
b72ff476 1657}
871ab9a3 1658?>