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