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