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