MDL-20636 Add missing defined('MOODLE_INTERNAL') || die();
[moodle.git] / question / editlib.php
CommitLineData
aeb15530 1<?php
f4b879dd 2
d1b7e03d
TH
3// This file is part of Moodle - http://moodle.org/
4//
5// Moodle is free software: you can redistribute it and/or modify
6// it under the terms of the GNU General Public License as published by
7// the Free Software Foundation, either version 3 of the License, or
8// (at your option) any later version.
9//
10// Moodle is distributed in the hope that it will be useful,
11// but WITHOUT ANY WARRANTY; without even the implied warranty of
12// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13// GNU General Public License for more details.
14//
15// You should have received a copy of the GNU General Public License
16// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
17
516cf3eb 18/**
b72ff476 19 * Functions used to show question editing interface
4323d029 20 *
d1b7e03d
TH
21 * @package moodlecore
22 * @subpackage questionbank
23 * @copyright 1999 onwards Martin Dougiamas and others {@link http://moodle.com}
24 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
25 */
26
516cf3eb 27
a17b297d 28defined('MOODLE_INTERNAL') || die();
516cf3eb 29
a17b297d 30require_once($CFG->libdir . '/questionlib.php');
d1b7e03d 31
f92cf442 32define('DEFAULT_QUESTIONS_PER_PAGE', 20);
33
f4b879dd 34function get_module_from_cmid($cmid) {
f34488b2 35 global $CFG, $DB;
36 if (!$cmrec = $DB->get_record_sql("SELECT cm.*, md.name as modname
37 FROM {course_modules} cm,
38 {modules} md
39 WHERE cm.id = ? AND
40 md.id = cm.module", array($cmid))){
1eda5201 41 print_error('invalidcoursemodule');
f34488b2 42 } elseif (!$modrec =$DB->get_record($cmrec->modname, array('id' => $cmrec->instance))) {
1eda5201 43 print_error('invalidcoursemodule');
86909ce0 44 }
45 $modrec->instance = $modrec->id;
d0e88092 46 $modrec->cmid = $cmrec->id;
ea16c547 47 $cmrec->name = $modrec->name;
271e6dec 48
86909ce0 49 return array($modrec, $cmrec);
50}
4fbfd971 51/**
52* Function to read all questions for category into big array
53*
54* @param int $category category number
36e2232e 55* @param bool $noparent if true only questions with NO parent will be selected
56* @param bool $recurse include subdirectories
5fd8f999 57* @param bool $export set true if this is called by questionbank export
4fbfd971 58* @author added by Howard Miller June 2004
59*/
5fd8f999 60function get_questions_category( $category, $noparent=false, $recurse=true, $export=true ) {
f9b0500f 61 global $DB;
4fbfd971 62
63 // questions will be added to an array
64 $qresults = array();
65
66 // build sql bit for $noparent
67 $npsql = '';
68 if ($noparent) {
69 $npsql = " and parent='0' ";
70 }
71
36e2232e 72 // get (list) of categories
73 if ($recurse) {
fe857668 74 $categorylist = question_categorylist($category->id);
36e2232e 75 }
76 else {
77 $categorylist = $category->id;
78 }
79
4fbfd971 80 // get the list of questions for the category
f34488b2 81 list ($usql, $params) = $DB->get_in_or_equal(explode(',', $categorylist));
82 if ($questions = $DB->get_records_select("question","category $usql $npsql", $params, "qtype, name ASC")) {
4fbfd971 83
84 // iterate through questions, getting stuff we need
85 foreach($questions as $question) {
5fd8f999 86 $question->export_process = $export;
f9b0500f 87 question_bank::get_qtype($question->qtype)->get_question_options($question);
4fbfd971 88 $qresults[] = $question;
89 }
90 }
91
92 return $qresults;
93}
94
df4e2244 95/**
96 * @param integer $categoryid a category id.
97 * @return boolean whether this is the only top-level category in a context.
98 */
99function question_is_only_toplevel_category_in_context($categoryid) {
100 global $DB;
101 return 1 == $DB->count_records_sql("
102 SELECT count(*)
103 FROM {question_categories} c1,
104 {question_categories} c2
105 WHERE c2.id = ?
106 AND c1.contextid = c2.contextid
107 AND c1.parent = 0 AND c2.parent = 0", array($categoryid));
108}
4fbfd971 109
df4e2244 110/**
111 * Check whether this user is allowed to delete this category.
112 *
113 * @param integer $todelete a category id.
114 */
115function question_can_delete_cat($todelete) {
116 global $DB;
117 if (question_is_only_toplevel_category_in_context($todelete)) {
ac93d63d 118 print_error('cannotdeletecate', 'question');
271e6dec 119 } else {
df4e2244 120 $contextid = $DB->get_field('question_categories', 'contextid', array('id' => $todelete));
271e6dec 121 require_capability('moodle/question:managecategory', get_context_instance_by_id($contextid));
122 }
123}
f4b879dd 124
46795afc 125abstract class question_bank_column_base {
e4d1d5e0 126 /**
127 * @var question_bank_view
128 */
5bd22790 129 protected $qbank;
130
131 /**
132 * Constructor.
133 * @param $qbank the question_bank_view we are helping to render.
134 */
135 public function __construct(question_bank_view $qbank) {
136 $this->qbank = $qbank;
137 $this->init();
138 }
139
140 /**
141 * A chance for subclasses to initialise themselves, for example to load lang strings,
142 * without having to override the constructor.
143 */
144 protected function init() {
145 }
46795afc 146
b7a9dc51 147 public function is_extra_row() {
148 return false;
149 }
150
46795afc 151 /**
152 * Output the column header cell.
153 * @param integer $currentsort 0 for none. 1 for normal sort, -1 for reverse sort.
154 */
5bd22790 155 public function display_header() {
b7a9dc51 156 echo '<th class="header ' . $this->get_classes() . '" scope="col">';
5bd22790 157 $sortable = $this->is_sortable();
158 $name = $this->get_name();
159 $title = $this->get_title();
e4d1d5e0 160 $tip = $this->get_title_tip();
5bd22790 161 if (is_array($sortable)) {
162 if ($title) {
163 echo '<div class="title">' . $title . '</div>';
164 }
165 $links = array();
166 foreach ($sortable as $subsort => $details) {
e4d1d5e0 167 $links[] = $this->make_sort_link($name . '_' . $subsort,
168 $details['title'], '', !empty($details['reverse']));
5bd22790 169 }
692d0480 170 echo '<div class="sorters">' . implode(' / ', $links) . '</div>';
5bd22790 171 } else if ($sortable) {
e4d1d5e0 172 echo $this->make_sort_link($name, $title, $tip);
5bd22790 173 } else {
0ff5afdf 174 if ($tip) {
175 echo '<span title="' . $tip . '">';
176 }
5bd22790 177 echo $title;
0ff5afdf 178 if ($tip) {
179 echo '</span>';
180 }
5bd22790 181 }
182 echo "</th>\n";
183 }
184
185 /**
186 * Title for this column. Not used if is_sortable returns an array.
187 * @param object $question the row from the $question table, augmented with extra information.
188 * @param string $rowclasses CSS class names that should be applied to this row of output.
189 */
971c6fca 190 abstract protected function get_title();
0ff5afdf 191
192 /**
193 * @return string a fuller version of the name. Use this when get_title() returns
194 * something very short, and you want a longer version as a tool tip.
195 */
196 protected function get_title_tip() {
5bd22790 197 return '';
198 }
199
200 /**
201 * Get a link that changes the sort order, and indicates the current sort state.
202 * @param $name internal name used for this type of sorting.
203 * @param $currentsort the current sort order -1, 0, 1 for descending, none, ascending.
204 * @param $title the link text.
205 * @param $defaultreverse whether the default sort order for this column is descending, rather than ascending.
206 * @return string HTML fragment.
207 */
e4d1d5e0 208 protected function make_sort_link($sort, $title, $tip, $defaultreverse = false) {
209 $currentsort = $this->qbank->get_primary_sort_order($sort);
5bd22790 210 $newsortreverse = $defaultreverse;
211 if ($currentsort) {
212 $newsortreverse = $currentsort > 0;
213 }
0ff5afdf 214 if (!$tip) {
215 $tip = $title;
216 }
5bd22790 217 if ($newsortreverse) {
0ff5afdf 218 $tip = get_string('sortbyxreverse', '', $tip);
5bd22790 219 } else {
0ff5afdf 220 $tip = get_string('sortbyx', '', $tip);
5bd22790 221 }
e4d1d5e0 222 $link = '<a href="' . $this->qbank->new_sort_url($sort, $newsortreverse) . '" title="' . $tip . '">';
223 $link .= $title;
5bd22790 224 if ($currentsort) {
e4d1d5e0 225 $link .= $this->get_sort_icon($currentsort < 0);
5bd22790 226 }
e4d1d5e0 227 $link .= '</a>';
228 return $link;
5bd22790 229 }
230
231 /**
232 * Get an icon representing the corrent sort state.
233 * @param $reverse sort is descending, not ascending.
234 * @return string HTML image tag.
235 */
236 protected function get_sort_icon($reverse) {
f2a1963c 237 global $OUTPUT;
5bd22790 238 if ($reverse) {
b5d0cafc 239 return ' <img src="' . $OUTPUT->pix_url('t/up') . '" alt="' . get_string('desc') . '" />';
5bd22790 240 } else {
b5d0cafc 241 return ' <img src="' . $OUTPUT->pix_url('t/down') . '" alt="' . get_string('asc') . '" />';
5bd22790 242 }
46795afc 243 }
244
245 /**
246 * Output this column.
247 * @param object $question the row from the $question table, augmented with extra information.
248 * @param string $rowclasses CSS class names that should be applied to this row of output.
249 */
250 public function display($question, $rowclasses) {
251 $this->display_start($question, $rowclasses);
252 $this->display_content($question, $rowclasses);
253 $this->display_end($question, $rowclasses);
254 }
255
256 protected function display_start($question, $rowclasses) {
b7a9dc51 257 echo '<td class="' . $this->get_classes() . '">';
258 }
259
260 /**
261 * @return string the CSS classes to apply to every cell in this column.
262 */
263 protected function get_classes() {
264 $classes = $this->get_extra_classes();
265 $classes[] = $this->get_name();
266 return implode(' ', $classes);
46795afc 267 }
268
269 /**
270 * @param object $question the row from the $question table, augmented with extra information.
b221dc6f 271 * @return string internal name for this column. Used as a CSS class name,
272 * and to store information about the current sort. Must match PARAM_ALPHA.
46795afc 273 */
babdcb40 274 abstract public function get_name();
46795afc 275
b7a9dc51 276 /**
277 * @return array any extra class names you would like applied to every cell in this column.
278 */
279 public function get_extra_classes() {
280 return array();
281 }
282
46795afc 283 /**
284 * Output the contents of this column.
285 * @param object $question the row from the $question table, augmented with extra information.
286 * @param string $rowclasses CSS class names that should be applied to this row of output.
287 */
288 abstract protected function display_content($question, $rowclasses);
289
290 protected function display_end($question, $rowclasses) {
5bd22790 291 echo "</td>\n";
46795afc 292 }
293
294 /**
295 * Return an array 'table_alias' => 'JOIN clause' to bring in any data that
296 * this column required.
297 *
298 * The return values for all the columns will be checked. It is OK if two
299 * columns join in the same table with the same alias and identical JOIN clauses.
300 * If to columns try to use the same alias with different joins, you get an error.
301 * The only table included by default is the question table, which is aliased to 'q'.
302 *
b221dc6f 303 * It is importnat that your join simply adds additional data (or NULLs) to the
304 * existing rows of the query. It must not cause additional rows.
305 *
46795afc 306 * @return array 'table_alias' => 'JOIN clause'
307 */
308 public function get_extra_joins() {
309 return array();
310 }
311
312 /**
313 * @return array fields required. use table alias 'q' for the question table, or one of the
314 * ones from get_extra_joins. Every field requested must specify a table prefix.
315 */
316 public function get_required_fields() {
317 return array();
318 }
319
320 /**
321 * Can this column be sorted on? You can return either:
322 * + false for no (the default),
5bd22790 323 * + a field name, if sorting this column corresponds to sorting on that datbase field.
324 * + an array of subnames to sort on as follows
325 * return array(
326 * 'firstname' => array('field' => 'uc.firstname', 'title' => get_string('firstname')),
327 * 'lastname' => array('field' => 'uc.lastname', 'field' => get_string('lastname')),
328 * );
329 * As well as field, and field, you can also add 'revers' => 1 if you want the default sort
330 * order to be DESC.
331 * @return mixed as above.
46795afc 332 */
333 public function is_sortable() {
334 return false;
335 }
336
337 /**
338 * Helper method for building sort clauses.
339 * @param boolean $reverse whether the normal direction should be reversed.
340 * @param string $normaldir 'ASC' or 'DESC'
341 * @return string 'ASC' or 'DESC'
342 */
5bd22790 343 protected function sortorder($reverse) {
344 if ($reverse) {
345 return ' DESC';
346 } else {
347 return ' ASC';
46795afc 348 }
349 }
350
351 /**
352 * @param $reverse Whether to sort in the reverse of the default sort order.
353 * @param $subsort if is_sortable returns an array of subnames, then this will be
354 * one of those. Otherwise will be empty.
355 * @return string some SQL to go in the order by clause.
356 */
357 public function sort_expression($reverse, $subsort) {
5bd22790 358 $sortable = $this->is_sortable();
359 if (is_array($sortable)) {
360 if (array_key_exists($subsort, $sortable)) {
e4d1d5e0 361 return $sortable[$subsort]['field'] . $this->sortorder($reverse, !empty($sortable[$subsort]['reverse']));
5bd22790 362 } else {
363 throw new coding_exception('Unexpected $subsort type: ' . $subsort);
364 }
365 } else if ($sortable) {
366 return $sortable . $this->sortorder($reverse);
367 } else {
368 throw new coding_exception('sort_expression called on a non-sortable column.');
369 }
46795afc 370 }
371}
372
373/**
374 * A column with a checkbox for each question with name q{questionid}.
375 */
376class question_bank_checkbox_column extends question_bank_column_base {
377 protected $strselect;
2d1e69d3 378 protected $firstrow = true;
46795afc 379
5bd22790 380 public function init() {
46795afc 381 $this->strselect = get_string('select', 'quiz');
382 }
383
babdcb40 384 public function get_name() {
46795afc 385 return 'checkbox';
386 }
387
5bd22790 388 protected function get_title() {
bfb1691d 389 return '<input type="checkbox" disabled="disabled" id="qbheadercheckbox" />';
5bd22790 390 }
391
0ff5afdf 392 protected function get_title_tip() {
393 return get_string('selectquestionsforbulk', 'question');
394 }
395
46795afc 396 protected function display_content($question, $rowclasses) {
cf615522 397 global $PAGE;
46795afc 398 echo '<input title="' . $this->strselect . '" type="checkbox" name="q' .
bfb1691d 399 $question->id . '" id="checkq' . $question->id . '" value="1"/>';
2d1e69d3 400 if ($this->firstrow) {
cf615522 401 $PAGE->requires->js_function_call('question_bank.init_checkbox_column', array(get_string('selectall'),
2d1e69d3 402 get_string('deselectall'), 'checkq' . $question->id));
403 $this->firstrow = false;
404 }
46795afc 405 }
406
407 public function get_required_fields() {
408 return array('q.id');
409 }
410}
411
412/**
413 * A column type for the name of the question type.
414 */
415class question_bank_question_type_column extends question_bank_column_base {
babdcb40 416 public function get_name() {
46795afc 417 return 'qtype';
418 }
419
5bd22790 420 protected function get_title() {
421 return get_string('qtypeveryshort', 'question');
422 }
423
0ff5afdf 424 protected function get_title_tip() {
425 return get_string('questiontype', 'question');
426 }
427
46795afc 428 protected function display_content($question, $rowclasses) {
429 echo print_question_icon($question);
430 }
431
432 public function get_required_fields() {
433 return array('q.qtype');
434 }
435
436 public function is_sortable() {
5bd22790 437 return 'q.qtype';
46795afc 438 }
439}
440
441/**
442 * A column type for the name of the question name.
443 */
444class question_bank_question_name_column extends question_bank_column_base {
971c6fca 445 protected $checkboxespresent = null;
446
babdcb40 447 public function get_name() {
46795afc 448 return 'questionname';
449 }
450
5bd22790 451 protected function get_title() {
452 return get_string('question');
453 }
454
971c6fca 455 protected function label_for($question) {
456 if (is_null($this->checkboxespresent)) {
457 $this->checkboxespresent = $this->qbank->has_column('checkbox');
458 }
459 if ($this->checkboxespresent) {
460 return 'checkq' . $question->id;
461 } else {
462 return '';
463 }
464 }
465
46795afc 466 protected function display_content($question, $rowclasses) {
971c6fca 467 $labelfor = $this->label_for($question);
468 if ($labelfor) {
469 echo '<label for="' . $labelfor . '">';
470 }
46795afc 471 echo format_string($question->name);
971c6fca 472 if ($labelfor) {
473 echo '</label>';
474 }
46795afc 475 }
476
477 public function get_required_fields() {
971c6fca 478 return array('q.id', 'q.name');
46795afc 479 }
480
481 public function is_sortable() {
5bd22790 482 return 'q.name';
46795afc 483 }
484}
485
486/**
487 * A column type for the name of the question creator.
488 */
489class question_bank_creator_name_column extends question_bank_column_base {
babdcb40 490 public function get_name() {
46795afc 491 return 'creatorname';
492 }
493
5bd22790 494 protected function get_title() {
495 return get_string('createdby', 'question');
496 }
497
46795afc 498 protected function display_content($question, $rowclasses) {
499 if (!empty($question->creatorfirstname) && !empty($question->creatorlastname)) {
0ff4bd08 500 $u = new stdClass();
46795afc 501 $u->firstname = $question->creatorfirstname;
502 $u->lastname = $question->creatorlastname;
503 echo fullname($u);
504 }
505 }
506
507 public function get_extra_joins() {
508 return array('uc' => 'LEFT JOIN {user} uc ON uc.id = q.createdby');
509 }
510
511 public function get_required_fields() {
512 return array('uc.firstname AS creatorfirstname', 'uc.lastname AS creatorlastname');
513 }
514
515 public function is_sortable() {
5bd22790 516 return array(
517 'firstname' => array('field' => 'uc.firstname', 'title' => get_string('firstname')),
518 'lastname' => array('field' => 'uc.lastname', 'title' => get_string('lastname')),
519 );
46795afc 520 }
521}
522
523/**
524 * A column type for the name of the question last modifier.
525 */
526class question_bank_modifier_name_column extends question_bank_column_base {
babdcb40 527 public function get_name() {
46795afc 528 return 'modifiername';
529 }
530
5bd22790 531 protected function get_title() {
532 return get_string('lastmodifiedby', 'question');
533 }
534
46795afc 535 protected function display_content($question, $rowclasses) {
536 if (!empty($question->modifierfirstname) && !empty($question->modifierlastname)) {
0ff4bd08 537 $u = new stdClass();
46795afc 538 $u->firstname = $question->modifierfirstname;
539 $u->lastname = $question->modifierlastname;
540 echo fullname($u);
541 }
542 }
543
544 public function get_extra_joins() {
545 return array('um' => 'LEFT JOIN {user} um ON um.id = q.modifiedby');
546 }
547
548 public function get_required_fields() {
549 return array('um.firstname AS modifierfirstname', 'um.lastname AS modifierlastname');
550 }
551
552 public function is_sortable() {
5bd22790 553 return array(
554 'firstname' => array('field' => 'um.firstname', 'title' => get_string('firstname')),
555 'lastname' => array('field' => 'um.lastname', 'title' => get_string('lastname')),
556 );
46795afc 557 }
558}
559
560/**
561 * A base class for actions that are an icon that lets you manipulate the question in some way.
562 */
563abstract class question_bank_action_column_base extends question_bank_column_base {
5bd22790 564
565 protected function get_title() {
566 return '&#160;';
567 }
568
b7a9dc51 569 public function get_extra_classes() {
570 return array('iconcol');
571 }
572
46795afc 573 protected function print_icon($icon, $title, $url) {
e63f88c9 574 global $OUTPUT;
46795afc 575 echo '<a title="' . $title . '" href="' . $url . '">
b5d0cafc 576 <img src="' . $OUTPUT->pix_url($icon) . '" class="iconsmall" alt="' . $title . '" /></a>';
46795afc 577 }
578
579 public function get_required_fields() {
580 return array('q.id');
581 }
582}
583
584class question_bank_edit_action_column extends question_bank_action_column_base {
585 protected $stredit;
586 protected $strview;
46795afc 587
5bd22790 588 public function init() {
589 parent::init();
46795afc 590 $this->stredit = get_string('edit');
591 $this->strview = get_string('view');
592 }
593
babdcb40 594 public function get_name() {
46795afc 595 return 'editaction';
596 }
597
598 protected function display_content($question, $rowclasses) {
599 if (question_has_capability_on($question, 'edit') ||
600 question_has_capability_on($question, 'move')) {
a28c9253 601 $this->print_icon('t/edit', $this->stredit, $this->qbank->edit_question_url($question->id));
46795afc 602 } else {
a28c9253 603 $this->print_icon('i/info', $this->strview, $this->qbank->edit_question_url($question->id));
46795afc 604 }
605 }
606}
607
608class question_bank_preview_action_column extends question_bank_action_column_base {
609 protected $strpreview;
46795afc 610
5bd22790 611 public function init() {
612 parent::init();
e4d1d5e0 613 $this->strpreview = get_string('preview');
46795afc 614 }
615
babdcb40 616 public function get_name() {
46795afc 617 return 'previewaction';
618 }
619
620 protected function display_content($question, $rowclasses) {
f2a1963c 621 global $OUTPUT;
46795afc 622 if (question_has_capability_on($question, 'use')) {
4bcc5118 623 // Build the icon.
000c278c 624 $image = $OUTPUT->pix_icon('t/preview', $this->strpreview);
80e7bb44 625
9bf16314 626 $link = new moodle_url($this->qbank->preview_question_url($question->id));
4bcc5118 627 parse_str(QUESTION_PREVIEW_POPUP_OPTIONS, $options);
9bf16314
PS
628 $action = new popup_action('click', $link, 'questionpreview', $options);
629
630 echo $OUTPUT->action_link($link, $image, $action, array('title' => $this->strpreview));
46795afc 631 }
632 }
633
634 public function get_required_fields() {
635 return array('q.id');
636 }
637}
638
639class question_bank_move_action_column extends question_bank_action_column_base {
640 protected $strmove;
46795afc 641
5bd22790 642 public function init() {
643 parent::init();
46795afc 644 $this->strmove = get_string('move');
645 }
646
babdcb40 647 public function get_name() {
648 return 'moveaction';
46795afc 649 }
650
651 protected function display_content($question, $rowclasses) {
652 if (question_has_capability_on($question, 'move')) {
a28c9253 653 $this->print_icon('t/move', $this->strmove, $this->qbank->move_question_url($question->id));
46795afc 654 }
655 }
656}
657
658/**
659 * action to delete (or hide) a question, or restore a previously hidden question.
660 */
661class question_bank_delete_action_column extends question_bank_action_column_base {
662 protected $strdelete;
663 protected $strrestore;
46795afc 664
5bd22790 665 public function init() {
666 parent::init();
46795afc 667 $this->strdelete = get_string('delete');
668 $this->strrestore = get_string('restore');
669 }
670
babdcb40 671 public function get_name() {
46795afc 672 return 'deleteaction';
673 }
674
675 protected function display_content($question, $rowclasses) {
676 if (question_has_capability_on($question, 'edit')) {
677 if ($question->hidden) {
8afba50b
PS
678 $url = new moodle_url($this->qbank->base_url(), array('unhide' => $question->id, 'sesskey'=>sesskey()));
679 $this->print_icon('t/restore', $this->strrestore, $url);
46795afc 680 } else {
8afba50b
PS
681 $url = new moodle_url($this->qbank->base_url(), array('deleteselected' => $question->id, 'q' . $question->id => 1, 'sesskey'=>sesskey()));
682 $this->print_icon('t/delete', $this->strdelete, $url);
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() {
0ff4bd08 721 $this->formatoptions = new stdClass();
b7a9dc51 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;
aa9c6ecf 779 protected $lastchangedid;
b221dc6f 780 protected $countsql;
781 protected $loadsql;
e4d1d5e0 782 protected $sqlparams;
5bd22790 783
971c6fca 784 public function __construct($contexts, $pageurl, $course, $cm = null) {
cf615522 785 global $CFG, $PAGE;
516cf3eb 786
5bd22790 787 $this->contexts = $contexts;
788 $this->baseurl = $pageurl;
971c6fca 789 $this->course = $course;
5bd22790 790 $this->cm = $cm;
791
792 if (!empty($cm) && $cm->modname == 'quiz') {
793 $this->quizorcourseid = '&amp;quizid=' . $cm->instance;
794 } else {
971c6fca 795 $this->quizorcourseid = '&amp;courseid=' .$this->course->id;
5bd22790 796 }
797
798 // Create the url of the new question page to forward to.
fb6dcdab 799 $returnurl = str_replace($CFG->wwwroot, '', $pageurl->out(false));
90c7912e
TH
800 $this->editquestionurl = new moodle_url('/question/question.php',
801 array('returnurl' => $returnurl));
5bd22790 802 if ($cm !== null){
803 $this->editquestionurl->param('cmid', $cm->id);
804 } else {
971c6fca 805 $this->editquestionurl->param('courseid', $this->course->id);
5bd22790 806 }
b221dc6f 807
aa9c6ecf 808 $this->lastchangedid = optional_param('lastchanged',0,PARAM_INT);
809
b221dc6f 810 $this->init_column_types();
971c6fca 811 $this->init_columns($this->wanted_columns());
b221dc6f 812 $this->init_sort();
cf615522 813
f44b10ed 814 $PAGE->requires->yui2_lib('container');
b221dc6f 815 }
816
971c6fca 817 protected function wanted_columns() {
1a9def7c
TH
818 $columns = array('checkbox', 'qtype', 'questionname', 'editaction',
819 'previewaction', 'moveaction', 'deleteaction', 'creatorname',
820 'modifiername');
b7a9dc51 821 if (optional_param('qbshowtext', false, PARAM_BOOL)) {
822 $columns[] = 'questiontext';
823 }
824 return $columns;
971c6fca 825 }
826
cd120b23 827 protected function known_field_types() {
971c6fca 828 return array(
b221dc6f 829 new question_bank_checkbox_column($this),
830 new question_bank_question_type_column($this),
831 new question_bank_question_name_column($this),
832 new question_bank_creator_name_column($this),
833 new question_bank_modifier_name_column($this),
834 new question_bank_edit_action_column($this),
835 new question_bank_preview_action_column($this),
836 new question_bank_move_action_column($this),
837 new question_bank_delete_action_column($this),
b7a9dc51 838 new question_bank_question_text_row($this),
b221dc6f 839 );
971c6fca 840 }
841
842 protected function init_column_types() {
b221dc6f 843 $this->knowncolumntypes = array();
cd120b23 844 foreach ($this->known_field_types() as $col) {
b221dc6f 845 $this->knowncolumntypes[$col->get_name()] = $col;
846 }
847 }
848
849 protected function init_columns($wanted) {
850 $this->visiblecolumns = array();
b7a9dc51 851 $this->extrarows = array();
b221dc6f 852 foreach ($wanted as $colname) {
853 if (!isset($this->knowncolumntypes[$colname])) {
854 throw new coding_exception('Unknown column type ' . $colname . ' requested in init columns.');
855 }
b7a9dc51 856 $column = $this->knowncolumntypes[$colname];
857 if ($column->is_extra_row()) {
858 $this->extrarows[$colname] = $column;
859 } else {
860 $this->visiblecolumns[$colname] = $column;
861 }
b221dc6f 862 }
b7a9dc51 863 $this->requiredcolumns = array_merge($this->visiblecolumns, $this->extrarows);
b221dc6f 864 }
865
e4d1d5e0 866 /**
867 * @param string $colname a column internal name.
868 * @return boolean is this column included in the output?
869 */
870 public function has_column($colname) {
871 return isset($this->visiblecolumns[$colname]);
872 }
873
b7a9dc51 874 /**
875 * @return integer The number of columns in the table.
876 */
877 public function get_column_count() {
878 return count($this->visiblecolumns);
879 }
880
881 public function get_courseid() {
882 return $this->course->id;
883 }
884
b221dc6f 885 protected function init_sort() {
886 $this->init_sort_from_params();
887 if (empty($this->sort)) {
888 $this->sort = $this->default_sort();
889 }
890 }
891
892 /**
893 * Deal with a sort name of the forum columnname, or colname_subsort by
894 * breaking it up, validating the bits that are presend, and returning them.
895 * If there is no subsort, then $subsort is returned as ''.
896 * @return array array($colname, $subsort).
897 */
898 protected function parse_subsort($sort) {
899 /// Do the parsing.
900 if (strpos($sort, '_') !== false) {
901 list($colname, $subsort) = explode('_', $sort, 2);
902 } else {
903 $colname = $sort;
904 $subsort = '';
905 }
906 /// Validate the column name.
907 if (!isset($this->knowncolumntypes[$colname]) || !$this->knowncolumntypes[$colname]->is_sortable()) {
e4d1d5e0 908 for ($i = 1; $i <= question_bank_view::MAX_SORTS; $i++) {
909 $this->baseurl->remove_params('qbs' . $i);
910 }
b221dc6f 911 throw new moodle_exception('unknownsortcolumn', '', $link = $this->baseurl->out(), $colname);
912 }
913 /// Validate the subsort, if present.
914 if ($subsort) {
915 $subsorts = $this->knowncolumntypes[$colname]->is_sortable();
916 if (!is_array($subsorts) || !isset($subsorts[$subsort])) {
917 throw new moodle_exception('unknownsortcolumn', '', $link = $this->baseurl->out(), $sort);
918 }
919 }
920 return array($colname, $subsort);
921 }
922
923 protected function init_sort_from_params() {
924 $this->sort = array();
e4d1d5e0 925 for ($i = 1; $i <= question_bank_view::MAX_SORTS; $i++) {
926 if (!$sort = optional_param('qbs' . $i, '', PARAM_ALPHAEXT)) {
b221dc6f 927 break;
928 }
929 // Work out the appropriate order.
930 $order = 1;
931 if ($sort[0] == '-') {
932 $order = -1;
e4d1d5e0 933 $sort = substr($sort, 1);
b221dc6f 934 if (!$sort) {
935 break;
936 }
937 }
938 // Deal with subsorts.
939 list($colname, $subsort) = $this->parse_subsort($sort);
940 $this->requiredcolumns[$colname] = $this->knowncolumntypes[$colname];
e4d1d5e0 941 $this->sort[$sort] = $order;
b221dc6f 942 }
943 }
944
e4d1d5e0 945 protected function sort_to_params($sorts) {
946 $params = array();
947 $i = 0;
948 foreach ($sorts as $sort => $order) {
949 $i += 1;
950 if ($order < 0) {
951 $sort = '-' . $sort;
952 }
953 $params['qbs' . $i] = $sort;
954 }
955 return $params;
956 }
957
b221dc6f 958 protected function default_sort() {
959 return array('qtype' => 1, 'questionname' => 1);
960 }
961
e4d1d5e0 962 /**
963 * @param $sort a column or column_subsort name.
964 * @return integer the current sort order for this column -1, 0, 1
965 */
966 public function get_primary_sort_order($sort) {
967 $order = reset($this->sort);
968 $primarysort = key($this->sort);
969 if ($sort == $primarysort) {
970 return $order;
971 } else {
972 return 0;
973 }
974 }
975
976 /**
977 * Get a URL to redisplay the page with a new sort for the question bank.
978 * @param string $sort the column, or column_subsort to sort on.
979 * @param boolean $newsortreverse whether to sort in reverse order.
980 * @return string The new URL.
981 */
982 public function new_sort_url($sort, $newsortreverse) {
983 if ($newsortreverse) {
984 $order = -1;
985 } else {
986 $order = 1;
987 }
988 // Tricky code to add the new sort at the start, removing it from where it was before, if it was present.
989 $newsort = array_reverse($this->sort);
990 if (isset($newsort[$sort])) {
991 unset($newsort[$sort]);
992 }
993 $newsort[$sort] = $order;
994 $newsort = array_reverse($newsort);
995 if (count($newsort) > question_bank_view::MAX_SORTS) {
996 $newsort = array_slice($newsort, 0, question_bank_view::MAX_SORTS, true);
997 }
b9bc2019 998 return $this->baseurl->out(true, $this->sort_to_params($newsort));
e4d1d5e0 999 }
1000
1001 protected function build_query_sql($category, $recurse, $showhidden) {
1002 global $DB;
1003
b221dc6f 1004 /// Get the required tables.
1005 $joins = array();
1006 foreach ($this->requiredcolumns as $column) {
1007 $extrajoins = $column->get_extra_joins();
1008 foreach ($extrajoins as $prefix => $join) {
1009 if (isset($joins[$prefix]) && $joins[$prefix] != $join) {
1010 throw new coding_exception('Join ' . $join . ' conflicts with previous join ' . $joins[$prefix]);
1011 }
1012 $joins[$prefix] = $join;
1013 }
1014 }
1015
1016 /// Get the required fields.
e4d1d5e0 1017 $fields = array('q.hidden', 'q.category');
b221dc6f 1018 foreach ($this->visiblecolumns as $column) {
e4d1d5e0 1019 $fields = array_merge($fields, $column->get_required_fields());
b221dc6f 1020 }
b7a9dc51 1021 foreach ($this->extrarows as $row) {
1022 $fields = array_merge($fields, $row->get_required_fields());
1023 }
b221dc6f 1024 $fields = array_unique($fields);
1025
1026 /// Build the order by clause.
1027 $sorts = array();
1028 foreach ($this->sort as $sort => $order) {
1029 list($colname, $subsort) = $this->parse_subsort($sort);
1030 $sorts[] = $this->knowncolumntypes[$colname]->sort_expression($order < 0, $subsort);
1031 }
1032
e4d1d5e0 1033 /// Build the where clause.
1034 $tests = array('parent = 0');
1035
331bcf9a 1036 if (!$showhidden) {
e4d1d5e0 1037 $tests[] = 'hidden = 0';
1038 }
1039
1040 if ($recurse) {
1041 $categoryids = explode(',', question_categorylist($category->id));
1042 } else {
1043 $categoryids = array($category->id);
1044 }
1045 list($catidtest, $params) = $DB->get_in_or_equal($categoryids, SQL_PARAMS_NAMED, 'cat0000');
1046 $tests[] = 'q.category ' . $catidtest;
1047 $this->sqlparams = $params;
1048
b221dc6f 1049 /// Build the SQL.
1050 $sql = ' FROM {question} q ' . implode(' ', $joins);
e4d1d5e0 1051 $sql .= ' WHERE ' . implode(' AND ', $tests);
b221dc6f 1052 $this->countsql = 'SELECT count(1)' . $sql;
e4d1d5e0 1053 $this->loadsql = 'SELECT ' . implode(', ', $fields) . $sql . ' ORDER BY ' . implode(', ', $sorts);
1054 $this->sqlparams = $params;
5bd22790 1055 }
1056
e4d1d5e0 1057 protected function get_question_count() {
1058 global $DB;
1059 return $DB->count_records_sql($this->countsql, $this->sqlparams);
1060 }
1061
1062 protected function load_page_questions($page, $perpage) {
1063 global $DB;
1064 $questions = $DB->get_recordset_sql($this->loadsql, $this->sqlparams, $page*$perpage, $perpage);
1065 if (!$questions->valid()) {
1066 /// No questions on this page. Reset to page 0.
1067 $questions = $DB->get_recordset_sql($this->loadsql, $this->sqlparams, 0, $perpage);
1068 }
1069 return $questions;
1070 }
1071
1072 public function base_url() {
1073 return $this->baseurl;
5bd22790 1074 }
1075
1076 public function edit_question_url($questionid) {
b9bc2019 1077 return $this->editquestionurl->out(true, array('id' => $questionid));
5bd22790 1078 }
1079
e4d1d5e0 1080 public function move_question_url($questionid) {
b9bc2019 1081 return $this->editquestionurl->out(true, array('id' => $questionid, 'movecontext' => 1));
e4d1d5e0 1082 }
1083
5bd22790 1084 public function preview_question_url($questionid) {
1085 global $CFG;
38e74ec4 1086 return $CFG->wwwroot . '/question/preview.php?id=' . $questionid . '&amp;courseid=' . $this->course->id;
f4b879dd 1087 }
516cf3eb 1088
f4b879dd 1089 /**
1090 * Shows the question bank editing interface.
1091 *
1092 * The function also processes a number of actions:
1093 *
1094 * Actions affecting the question pool:
1095 * move Moves a question to a different category
1096 * deleteselected Deletes the selected questions from the category
1097 * Other actions:
1098 * category Chooses the category
1099 * displayoptions Sets display options
f4b879dd 1100 */
5bd22790 1101 public function display($tabname, $page, $perpage, $sortorder,
f4b879dd 1102 $sortorderdecoded, $cat, $recurse, $showhidden, $showquestiontext){
723d610c 1103 global $PAGE, $OUTPUT;
f4b879dd 1104
5bd22790 1105 if ($this->process_actions_needing_ui()) {
5b5e5ab2 1106 return;
f4b879dd 1107 }
516cf3eb 1108
9dec75db 1109 $PAGE->requires->js('/question/qbank.js');
25ddb7ef 1110
5b5e5ab2 1111 // Category selection form
723d610c 1112 echo $OUTPUT->heading(get_string('questionbank', 'question'), 2);
5b5e5ab2 1113
5bd22790 1114 $this->display_category_form($this->contexts->having_one_edit_tab_cap($tabname),
971c6fca 1115 $this->baseurl, $cat);
1116 $this->display_options($recurse, $showhidden, $showquestiontext);
1117
1118 if (!$category = $this->get_current_category($cat)) {
1119 return;
1120 }
1121 $this->print_category_info($category);
624cbc9c 1122
f4b879dd 1123 // continues with list of questions
5bd22790 1124 $this->display_question_list($this->contexts->having_one_edit_tab_cap($tabname), $this->baseurl, $cat, $this->cm,
f4b879dd 1125 $recurse, $page, $perpage, $showhidden, $sortorder, $sortorderdecoded, $showquestiontext,
5bd22790 1126 $this->contexts->having_cap('moodle/question:add'));
516cf3eb 1127 }
1128
971c6fca 1129 protected function print_choose_category_message($categoryandcontext) {
1130 echo "<p style=\"text-align:center;\"><b>";
1131 print_string("selectcategoryabove", "quiz");
1132 echo "</b></p>";
1133 }
1134
1135 protected function get_current_category($categoryandcontext) {
beb677cd 1136 global $DB, $OUTPUT;
971c6fca 1137 list($categoryid, $contextid) = explode(',', $categoryandcontext);
1138 if (!$categoryid) {
1139 $this->print_choose_category_message($categoryandcontext);
1140 return false;
1141 }
1142
1143 if (!$category = $DB->get_record('question_categories',
1144 array('id' => $categoryid, 'contextid' => $contextid))) {
beb677cd 1145 echo $OUTPUT->box_start('generalbox questionbank');
fef8f84e 1146 echo $OUTPUT->notification('Category not found!');
beb677cd 1147 echo $OUTPUT->box_end();
971c6fca 1148 return false;
1149 }
1150
1151 return $category;
1152 }
1153
1154 protected function print_category_info($category) {
0ff4bd08 1155 $formatoptions = new stdClass();
971c6fca 1156 $formatoptions->noclean = true;
367a75fa 1157 $formatoptions->overflowdiv = true;
971c6fca 1158 echo '<div class="boxaligncenter">';
1159 echo format_text($category->info, FORMAT_MOODLE, $formatoptions, $this->course->id);
1160 echo "</div>\n";
1161 }
1162
f4b879dd 1163 /**
1164 * prints a form to choose categories
1165 */
971c6fca 1166 protected function display_category_form($contexts, $pageurl, $current) {
68e90fcc 1167 global $CFG, $OUTPUT;
516cf3eb 1168
f4b879dd 1169 /// Get all the existing categories now
cd120b23 1170 echo '<div class="choosecategory">';
f4b879dd 1171 $catmenu = question_category_options($contexts, false, 0, true);
0fd3556d 1172
fa16dd3d 1173 $select = new single_select($this->baseurl, 'category', $catmenu, $current, null, 'catmenu');
68e90fcc 1174 $select->set_label(get_string('selectacategory', 'question'));
94fa6be4 1175 echo $OUTPUT->render($select);
cd120b23 1176 echo "</div>\n";
971c6fca 1177 }
f4b879dd 1178
971c6fca 1179 protected function display_options($recurse = 1, $showhidden = false, $showquestiontext = false) {
f4b879dd 1180 echo '<form method="get" action="edit.php" id="displayoptions">';
1181 echo "<fieldset class='invisiblefieldset'>";
6ea66ff3 1182 echo html_writer::input_hidden_params($this->baseurl, array('recurse', 'showhidden', 'showquestiontext'));
b7a9dc51 1183 $this->display_category_form_checkbox('recurse', get_string('recurse', 'quiz'));
1184 $this->display_category_form_checkbox('showhidden', get_string('showhidden', 'quiz'));
1185 $this->display_category_form_checkbox('qbshowtext', get_string('showquestiontext', 'quiz'));
f4b879dd 1186 echo '<noscript><div class="centerpara"><input type="submit" value="'. get_string('go') .'" />';
1187 echo '</div></noscript></fieldset></form>';
516cf3eb 1188 }
1189
f4b879dd 1190 /**
971c6fca 1191 * Print a single option checkbox. Used by the preceeding.
f4b879dd 1192 */
b7a9dc51 1193 protected function display_category_form_checkbox($name, $label) {
f4b879dd 1194 echo '<div><input type="hidden" id="' . $name . '_off" name="' . $name . '" value="0" />';
1195 echo '<input type="checkbox" id="' . $name . '_on" name="' . $name . '" value="1"';
b7a9dc51 1196 if (optional_param($name, false, PARAM_BOOL)) {
f4b879dd 1197 echo ' checked="checked"';
516cf3eb 1198 }
f4b879dd 1199 echo ' onchange="getElementById(\'displayoptions\').submit(); return true;" />';
b7a9dc51 1200 echo '<label for="' . $name . '_on">' . $label . '</label>';
1201 echo "</div>\n";
516cf3eb 1202 }
1203
e4d1d5e0 1204 protected function create_new_question_form($category, $canadd) {
cd120b23 1205 global $CFG;
e4d1d5e0 1206 echo '<div class="createnewquestion">';
1207 if ($canadd) {
cd120b23 1208 create_new_question_button($category->id, $this->editquestionurl->params(),
1209 get_string('createnewquestion', 'question'));
e4d1d5e0 1210 } else {
1211 print_string('nopermissionadd', 'question');
1212 }
1213 echo '</div>';
1214 }
1215
f4b879dd 1216 /**
1217 * Prints the table of questions in a category with interactions
1218 *
1219 * @param object $course The course object
1220 * @param int $categoryid The id of the question category to be displayed
1221 * @param int $cm The course module record if we are in the context of a particular module, 0 otherwise
1222 * @param int $recurse This is 1 if subcategories should be included, 0 otherwise
1223 * @param int $page The number of the page to be displayed
1224 * @param int $perpage Number of questions to show per page
1225 * @param boolean $showhidden True if also hidden questions should be displayed
1226 * @param boolean $showquestiontext whether the text of each question should be shown in the list
1227 */
5bd22790 1228 protected function display_question_list($contexts, $pageurl, $categoryandcontext,
5b5e5ab2 1229 $cm = null, $recurse=1, $page=0, $perpage=100, $showhidden=false,
1230 $sortorder='typename', $sortorderdecoded='qtype, name ASC',
f4b879dd 1231 $showquestiontext = false, $addcontexts = array()) {
bda3e711 1232 global $CFG, $DB, $OUTPUT;
f4b879dd 1233
e4d1d5e0 1234 $category = $this->get_current_category($categoryandcontext);
f4b879dd 1235
0ff4bd08 1236 $cmoptions = new stdClass();
971c6fca 1237 $cmoptions->hasattempts = !empty($this->quizhasattempts);
1238
f4b879dd 1239 $strselectall = get_string("selectall", "quiz");
1240 $strselectnone = get_string("selectnone", "quiz");
f4b879dd 1241 $strdelete = get_string("delete");
5b5e5ab2 1242
e4d1d5e0 1243 list($categoryid, $contextid) = explode(',', $categoryandcontext);
f4b879dd 1244 $catcontext = get_context_instance_by_id($contextid);
e4d1d5e0 1245
f4b879dd 1246 $canadd = has_capability('moodle/question:add', $catcontext);
f4b879dd 1247 $caneditall =has_capability('moodle/question:editall', $catcontext);
1248 $canuseall =has_capability('moodle/question:useall', $catcontext);
1249 $canmoveall =has_capability('moodle/question:moveall', $catcontext);
1250
e4d1d5e0 1251 $this->create_new_question_form($category, $canadd);
f4b879dd 1252
e4d1d5e0 1253 $this->build_query_sql($category, $recurse, $showhidden);
1254 $totalnumber = $this->get_question_count();
1255 if ($totalnumber == 0) {
f4b879dd 1256 return;
271e6dec 1257 }
1258
e4d1d5e0 1259 $questions = $this->load_page_questions($page, $perpage);
5b5e5ab2 1260
1261 echo '<div class="categorypagingbarcontainer">';
d6d8b94c 1262 $pageing_url = new moodle_url('edit.php');
1263 $r = $pageing_url->params($pageurl->params());
929d7a83 1264 $pagingbar = new paging_bar($totalnumber, $page, $perpage, $pageing_url);
9c7886e7 1265 $pagingbar->pagevar = 'qpage';
929d7a83 1266 echo $OUTPUT->render($pagingbar);
5b5e5ab2 1267 echo '</div>';
f4b879dd 1268
1269 echo '<form method="post" action="edit.php">';
1270 echo '<fieldset class="invisiblefieldset" style="display: block;">';
1271 echo '<input type="hidden" name="sesskey" value="'.sesskey().'" />';
6ea66ff3 1272 echo html_writer::input_hidden_params($pageurl);
f4b879dd 1273
cd120b23 1274 echo '<div class="categoryquestionscontainer">';
e4d1d5e0 1275 $this->start_table();
b7a9dc51 1276 $rowcount = 0;
f4b879dd 1277 foreach ($questions as $question) {
b7a9dc51 1278 $this->print_table_row($question, $rowcount);
1279 $rowcount += 1;
271e6dec 1280 }
e4d1d5e0 1281 $this->end_table();
cd120b23 1282 echo "</div>\n";
86909ce0 1283
5b5e5ab2 1284 echo '<div class="categorypagingbarcontainer pagingbottom">';
929d7a83 1285 echo $OUTPUT->render($pagingbar);
f4b879dd 1286 if ($totalnumber > DEFAULT_QUESTIONS_PER_PAGE) {
1287 if ($perpage == DEFAULT_QUESTIONS_PER_PAGE) {
8afba50b
PS
1288 $url = new moodle_url('edit.php', ($pageurl->params()+array('qperpage'=>1000)));
1289 $showall = '<a href="'.$url.'">'.get_string('showall', 'moodle', $totalnumber).'</a>';
f4b879dd 1290 } else {
8afba50b
PS
1291 $url = new moodle_url('edit.php', ($pageurl->params()+array('qperpage'=>DEFAULT_QUESTIONS_PER_PAGE)));
1292 $showall = '<a href="'.$url.'">'.get_string('showperpage', 'moodle', DEFAULT_QUESTIONS_PER_PAGE).'</a>';
f4b879dd 1293 }
b0f4e4e4 1294 echo "<div class='paging'>$showall</div>";
86909ce0 1295 }
5b5e5ab2 1296 echo '</div>';
f4b879dd 1297
5b5e5ab2 1298 echo '<div class="modulespecificbuttonscontainer">';
1299 if ($caneditall || $canmoveall || $canuseall){
f4b879dd 1300 echo '<strong>&nbsp;'.get_string('withselected', 'quiz').':</strong><br />';
1301
1302 if (function_exists('module_specific_buttons')) {
971c6fca 1303 echo module_specific_buttons($this->cm->id,$cmoptions);
f4b879dd 1304 }
5b5e5ab2 1305
f4b879dd 1306 // print delete and move selected question
1307 if ($caneditall) {
5b5e5ab2 1308 echo '<input type="submit" name="deleteselected" value="' . $strdelete . "\" />\n";
f4b879dd 1309 }
5b5e5ab2 1310
f4b879dd 1311 if ($canmoveall && count($addcontexts)) {
1312 echo '<input type="submit" name="move" value="'.get_string('moveto', 'quiz')."\" />\n";
1313 question_category_select_menu($addcontexts, false, 0, "$category->id,$category->contextid");
1314 }
1315
1316 if (function_exists('module_specific_controls') && $canuseall) {
971c6fca 1317 $modulespecific = module_specific_controls($totalnumber, $recurse, $category, $this->cm->id,$cmoptions);
5b5e5ab2 1318 if(!empty($modulespecific)){
1319 echo "<hr />$modulespecific";
1320 }
271e6dec 1321 }
1322 }
5b5e5ab2 1323 echo "</div>\n";
1324
f4b879dd 1325 echo '</fieldset>';
1326 echo "</form>\n";
1327 }
1328
e4d1d5e0 1329 protected function start_table() {
1330 echo '<table id="categoryquestions">' . "\n";
1331 echo "<thead>\n";
1332 $this->print_table_headers();
1333 echo "</thead>\n";
1334 echo "<tbody>\n";
1335 }
1336
1337 protected function end_table() {
1338 echo "</tbody>\n";
1339 echo "</table>\n";
1340 }
1341
1342 protected function print_table_headers() {
1343 echo "<tr>\n";
1344 foreach ($this->visiblecolumns as $column) {
1345 $column->display_header();
1346 }
1347 echo "</tr>\n";
1348 }
1349
b7a9dc51 1350 protected function get_row_classes($question, $rowcount) {
e4d1d5e0 1351 $classes = array();
1352 if ($question->hidden) {
1353 $classes[] = 'dimmed_text';
1354 }
aa9c6ecf 1355 if ($question->id == $this->lastchangedid) {
aa37f5e3 1356 $classes[] ='highlight';
aa9c6ecf 1357 }
b7a9dc51 1358 if (!empty($this->extrarows)) {
1359 $classes[] = 'r' . ($rowcount % 2);
1360 }
e4d1d5e0 1361 return $classes;
1362 }
1363
b7a9dc51 1364 protected function print_table_row($question, $rowcount) {
1365 $rowclasses = implode(' ', $this->get_row_classes($question, $rowcount));
e4d1d5e0 1366 if ($rowclasses) {
1367 echo '<tr class="' . $rowclasses . '">' . "\n";
1368 } else {
1369 echo "<tr>\n";
1370 }
1371 foreach ($this->visiblecolumns as $column) {
1372 $column->display($question, $rowclasses);
1373 }
1374 echo "</tr>\n";
b7a9dc51 1375 foreach ($this->extrarows as $row) {
1376 $row->display($question, $rowclasses);
1377 }
f4b879dd 1378 }
1379
5bd22790 1380 public function process_actions() {
971c6fca 1381 global $CFG, $DB;
f4b879dd 1382 /// Now, check for commands on this page and modify variables as necessary
5d548d3e
TH
1383 if (optional_param('move', false, PARAM_BOOL) and confirm_sesskey()) {
1384 // Move selected questions to new category
f4b879dd 1385 $category = required_param('category', PARAM_SEQUENCE);
1386 list($tocategoryid, $contextid) = explode(',', $category);
1387 if (! $tocategory = $DB->get_record('question_categories', array('id' => $tocategoryid, 'contextid' => $contextid))) {
1388 print_error('cannotfindcate', 'question');
271e6dec 1389 }
f4b879dd 1390 $tocontext = get_context_instance_by_id($contextid);
1391 require_capability('moodle/question:add', $tocontext);
1392 $rawdata = (array) data_submitted();
1393 $questionids = array();
1394 foreach ($rawdata as $key => $value) { // Parse input for question ids
1395 if (preg_match('!^q([0-9]+)$!', $key, $matches)) {
1396 $key = $matches[1];
1397 $questionids[] = $key;
271e6dec 1398 }
1399 }
fe6ce234 1400 if ($questionids) {
f4b879dd 1401 list($usql, $params) = $DB->get_in_or_equal($questionids);
5d548d3e
TH
1402 $sql = "";
1403 $questions = $DB->get_records_sql("
1404 SELECT q.*, c.contextid
1405 FROM {question} q
1406 JOIN {question_categories} c ON c.id = q.category
1407 WHERE q.id $usql", $params);
f4b879dd 1408 foreach ($questions as $question){
f4b879dd 1409 question_require_capability_on($question, 'move');
86909ce0 1410 }
5d548d3e
TH
1411 question_move_questions_to_category($questionids, $tocategory->id);
1412 redirect($this->baseurl->out(false,
1413 array('category' => "$tocategoryid,$contextid")));
86909ce0 1414 }
1415 }
86909ce0 1416
f4b879dd 1417 if (optional_param('deleteselected', false, PARAM_BOOL)) { // delete selected questions from the category
1418 if (($confirm = optional_param('confirm', '', PARAM_ALPHANUM)) and confirm_sesskey()) { // teacher has already confirmed the action
622365d2 1419 $deleteselected = required_param('deleteselected', PARAM_RAW);
f4b879dd 1420 if ($confirm == md5($deleteselected)) {
1421 if ($questionlist = explode(',', $deleteselected)) {
1422 // for each question either hide it if it is in use or delete it
1423 foreach ($questionlist as $questionid) {
4454447d 1424 $questionid = (int)$questionid;
f4b879dd 1425 question_require_capability_on($questionid, 'edit');
d1b7e03d 1426 if (questions_in_use(array($questionid))) {
f685e830 1427 $DB->set_field('question', 'hidden', 1, array('id' => $questionid));
f4b879dd 1428 } else {
d1b7e03d 1429 question_delete_question($questionid);
86909ce0 1430 }
86909ce0 1431 }
1432 }
c9f15305 1433 redirect($this->baseurl);
f4b879dd 1434 } else {
1435 print_error('invalidconfirm', 'question');
86909ce0 1436 }
86909ce0 1437 }
86909ce0 1438 }
8e77884c 1439
f4b879dd 1440 // Unhide a question
1441 if(($unhide = optional_param('unhide', '', PARAM_INT)) and confirm_sesskey()) {
1442 question_require_capability_on($unhide, 'edit');
f685e830 1443 $DB->set_field('question', 'hidden', 0, array('id' => $unhide));
c9f15305 1444 redirect($this->baseurl);
271e6dec 1445 }
271e6dec 1446 }
5bd22790 1447
1448 public function process_actions_needing_ui() {
a941387a 1449 global $DB, $OUTPUT;
5bd22790 1450 if (optional_param('deleteselected', false, PARAM_BOOL)) {
1451 // make a list of all the questions that are selected
1452 $rawquestions = $_REQUEST; // This code is called by both POST forms and GET links, so cannot use data_submitted.
1453 $questionlist = ''; // comma separated list of ids of questions to be deleted
1454 $questionnames = ''; // string with names of questions separated by <br /> with
1455 // an asterix in front of those that are in use
1456 $inuse = false; // set to true if at least one of the questions is in use
1457 foreach ($rawquestions as $key => $value) { // Parse input for question ids
1458 if (preg_match('!^q([0-9]+)$!', $key, $matches)) {
1459 $key = $matches[1];
1460 $questionlist .= $key.',';
1461 question_require_capability_on($key, 'edit');
d1b7e03d 1462 if (questions_in_use(array($key))) {
5bd22790 1463 $questionnames .= '* ';
1464 $inuse = true;
1465 }
1466 $questionnames .= $DB->get_field('question', 'name', array('id' => $key)) . '<br />';
1467 }
1468 }
1469 if (!$questionlist) { // no questions were selected
c9f15305 1470 redirect($this->baseurl);
5bd22790 1471 }
1472 $questionlist = rtrim($questionlist, ',');
1473
1474 // Add an explanation about questions in use
1475 if ($inuse) {
1476 $questionnames .= '<br />'.get_string('questionsinuse', 'quiz');
1477 }
8afba50b
PS
1478 $baseurl = new moodle_url('edit.php', $this->baseurl->params());
1479 $deleteurl = new moodle_url($baseurl, array('deleteselected'=>$questionlist, 'confirm'=>md5($questionlist), 'sesskey'=>sesskey()));
aeb15530 1480
8afba50b 1481 echo $OUTPUT->confirm(get_string("deletequestionscheck", "quiz", $questionnames), $deleteurl, $baseurl);
5bd22790 1482
1483 return true;
1484 }
1485 }
86909ce0 1486}
f4b879dd 1487
b72ff476 1488/**
1489 * Common setup for all pages for editing questions.
453b28d8 1490 * @param string $baseurl the name of the script calling this funciton. For examle 'qusetion/edit.php'.
271e6dec 1491 * @param string $edittab code for this edit tab
b72ff476 1492 * @param boolean $requirecmid require cmid? default false
1493 * @param boolean $requirecourseid require courseid, if cmid is not given? default true
271e6dec 1494 * @return array $thispageurl, $contexts, $cmid, $cm, $module, $pagevars
b72ff476 1495 */
453b28d8 1496function question_edit_setup($edittab, $baseurl, $requirecmid = false, $requirecourseid = true) {
56ed242b 1497 global $DB, $PAGE;
271e6dec 1498
1499 //$thispageurl is used to construct urls for all question edit pages we link to from this page. It contains an array
36e298bc 1500 //of parameters that are passed from page to page.
453b28d8
TH
1501// $thispageurl = new moodle_url($PAGE->url); //TODO: this looks dumb, because this method is called BEFORE $PAGE->set_page() !!!!
1502 $thispageurl = new moodle_url($baseurl);
47ce714b 1503 $thispageurl->remove_all_params(); // We are going to explicity add back everything important - this avoids unwanted params from being retained.
b4a2e413 1504
b72ff476 1505 if ($requirecmid){
1506 $cmid =required_param('cmid', PARAM_INT);
1507 } else {
1508 $cmid = optional_param('cmid', 0, PARAM_INT);
1509 }
1510 if ($cmid){
271e6dec 1511 list($module, $cm) = get_module_from_cmid($cmid);
b72ff476 1512 $courseid = $cm->course;
1513 $thispageurl->params(compact('cmid'));
271e6dec 1514 require_login($courseid, false, $cm);
1515 $thiscontext = get_context_instance(CONTEXT_MODULE, $cmid);
b72ff476 1516 } else {
1517 $module = null;
1518 $cm = null;
1519 if ($requirecourseid){
1520 $courseid = required_param('courseid', PARAM_INT);
1521 } else {
1522 $courseid = optional_param('courseid', 0, PARAM_INT);
1523 }
1524 if ($courseid){
1525 $thispageurl->params(compact('courseid'));
271e6dec 1526 require_login($courseid, false);
1527 $thiscontext = get_context_instance(CONTEXT_COURSE, $courseid);
1528 } else {
1529 $thiscontext = null;
b72ff476 1530 }
1531 }
e044ebb4
TH
1532 if (strpos($baseurl, '/question/') === 0) {
1533 navigation_node::override_active_url($thispageurl);
1534 }
271e6dec 1535
1536 if ($thiscontext){
1537 $contexts = new question_edit_contexts($thiscontext);
1538 $contexts->require_one_edit_tab_cap($edittab);
1539
1540 } else {
1541 $contexts = null;
1542 }
1543
1544
1545
36e298bc 1546 $pagevars['qpage'] = optional_param('qpage', -1, PARAM_INT);
271e6dec 1547
7bc26c8f 1548 //pass 'cat' from page to page and when 'category' comes from a drop down menu
271e6dec 1549 //then we also reset the qpage so we go to page 1 of
7bc26c8f 1550 //a new cat.
271e6dec 1551 $pagevars['cat'] = optional_param('cat', 0, PARAM_SEQUENCE);// if empty will be set up later
1552 if ($category = optional_param('category', 0, PARAM_SEQUENCE)){
a18fbcfb 1553 if ($pagevars['cat'] != $category){ // is this a move to a new category?
1554 $pagevars['cat'] = $category;
1555 $pagevars['qpage'] = 0;
1556 }
7bc26c8f 1557 }
1558 if ($pagevars['cat']){
1559 $thispageurl->param('cat', $pagevars['cat']);
1560 }
b72ff476 1561 if ($pagevars['qpage'] > -1) {
1562 $thispageurl->param('qpage', $pagevars['qpage']);
1563 } else {
1564 $pagevars['qpage'] = 0;
1565 }
1566
36e298bc 1567 $pagevars['qperpage'] = optional_param('qperpage', -1, PARAM_INT);
b72ff476 1568 if ($pagevars['qperpage'] > -1) {
1569 $thispageurl->param('qperpage', $pagevars['qperpage']);
1570 } else {
1571 $pagevars['qperpage'] = DEFAULT_QUESTIONS_PER_PAGE;
1572 }
271e6dec 1573
36e298bc 1574 $sortoptions = array('alpha' => 'name, qtype ASC',
1575 'typealpha' => 'qtype, name ASC',
1576 'age' => 'id ASC');
1577
1578 if ($sortorder = optional_param('qsortorder', '', PARAM_ALPHA)) {
1579 $pagevars['qsortorderdecoded'] = $sortoptions[$sortorder];
1580 $pagevars['qsortorder'] = $sortorder;
1581 $thispageurl->param('qsortorder', $sortorder);
b72ff476 1582 } else {
7bc26c8f 1583 $pagevars['qsortorderdecoded'] = $sortoptions['typealpha'];
1584 $pagevars['qsortorder'] = 'typealpha';
271e6dec 1585 }
36e298bc 1586
271e6dec 1587 $defaultcategory = question_make_default_categories($contexts->all());
1588
1589 $contextlistarr = array();
1590 foreach ($contexts->having_one_edit_tab_cap($edittab) as $context){
1591 $contextlistarr[] = "'$context->id'";
1592 }
1593 $contextlist = join($contextlistarr, ' ,');
1594 if (!empty($pagevars['cat'])){
1595 $catparts = explode(',', $pagevars['cat']);
f34488b2 1596 if (!$catparts[0] || (FALSE !== array_search($catparts[1], $contextlistarr)) ||
1597 !$DB->count_records_select("question_categories", "id = ? AND contextid = ?", array($catparts[0], $catparts[1]))) {
5a2a5331 1598 print_error('invalidcategory', 'quiz');
271e6dec 1599 }
1600 } else {
1601 $category = $defaultcategory;
1602 $pagevars['cat'] = "$category->id,$category->contextid";
36e298bc 1603 }
1604
1605 if(($recurse = optional_param('recurse', -1, PARAM_BOOL)) != -1) {
1606 $pagevars['recurse'] = $recurse;
1607 $thispageurl->param('recurse', $recurse);
1608 } else {
1609 $pagevars['recurse'] = 1;
1610 }
271e6dec 1611
36e298bc 1612 if(($showhidden = optional_param('showhidden', -1, PARAM_BOOL)) != -1) {
1613 $pagevars['showhidden'] = $showhidden;
1614 $thispageurl->param('showhidden', $showhidden);
1615 } else {
1616 $pagevars['showhidden'] = 0;
1617 }
271e6dec 1618
36e298bc 1619 if(($showquestiontext = optional_param('showquestiontext', -1, PARAM_BOOL)) != -1) {
1620 $pagevars['showquestiontext'] = $showquestiontext;
1621 $thispageurl->param('showquestiontext', $showquestiontext);
1622 } else {
1623 $pagevars['showquestiontext'] = 0;
1624 }
271e6dec 1625
986effb6 1626 //category list page
1627 $pagevars['cpage'] = optional_param('cpage', 1, PARAM_INT);
1628 if ($pagevars['cpage'] != 1){
1629 $thispageurl->param('cpage', $pagevars['cpage']);
1630 }
36e298bc 1631
271e6dec 1632 return array($thispageurl, $contexts, $cmid, $cm, $module, $pagevars);
1633}
271e6dec 1634
56ed242b
SH
1635/**
1636 * Required for legacy reasons. Was originally global then changed to class static
1637 * as of Moodle 2.0
1638 */
1639$QUESTION_EDITTABCAPS = question_edit_contexts::$CAPS;
271e6dec 1640
1641/**
1642 * Make sure user is logged in as required in this context.
1643 */
1644function require_login_in_context($contextorid = null){
042a8403 1645 global $DB, $CFG;
271e6dec 1646 if (!is_object($contextorid)){
1647 $context = get_context_instance_by_id($contextorid);
1648 } else {
1649 $context = $contextorid;
1650 }
1651 if ($context && ($context->contextlevel == CONTEXT_COURSE)) {
1652 require_login($context->instanceid);
1653 } else if ($context && ($context->contextlevel == CONTEXT_MODULE)) {
f34488b2 1654 if ($cm = $DB->get_record('course_modules',array('id' =>$context->instanceid))) {
1655 if (!$course = $DB->get_record('course', array('id' => $cm->course))) {
0be2c858 1656 print_error('invalidcourseid');
271e6dec 1657 }
1658 require_course_login($course, true, $cm);
1659
1660 } else {
0be2c858 1661 print_error('invalidcoursemodule');
271e6dec 1662 }
1663 } else if ($context && ($context->contextlevel == CONTEXT_SYSTEM)) {
1664 if (!empty($CFG->forcelogin)) {
1665 require_login();
1666 }
1667
1668 } else {
1669 require_login();
1670 }
b72ff476 1671}
cd120b23 1672
1673/**
1674 * Print a form to let the user choose which question type to add.
1675 * When the form is submitted, it goes to the question.php script.
1676 * @param $hiddenparams hidden parameters to add to the form, in addition to
1677 * the qtype radio buttons.
1678 */
1679function print_choose_qtype_to_add_form($hiddenparams) {
f9b0500f 1680 global $CFG, $PAGE, $OUTPUT;
9dec75db 1681 $PAGE->requires->js('/question/qbank.js');
cd120b23 1682 echo '<div id="chooseqtypehead" class="hd">' . "\n";
723d610c 1683 echo $OUTPUT->heading(get_string('chooseqtypetoadd', 'question'), 3);
cd120b23 1684 echo "</div>\n";
1685 echo '<div id="chooseqtype">' . "\n";
1686 echo '<form action="' . $CFG->wwwroot . '/question/question.php" method="get"><div id="qtypeformdiv">' . "\n";
1687 foreach ($hiddenparams as $name => $value) {
1688 echo '<input type="hidden" name="' . s($name) . '" value="' . s($value) . '" />' . "\n";
1689 }
1690 echo "</div>\n";
cd120b23 1691 echo '<div class="qtypes">' . "\n";
1692 echo '<div class="instruction">' . get_string('selectaqtypefordescription', 'question') . "</div>\n";
b974f947 1693 echo '<div class="realqtypes">' . "\n";
b974f947 1694 $fakeqtypes = array();
f9b0500f 1695 foreach (question_bank::get_creatable_qtypes() as $qtype) {
a13d4fbd 1696 if ($qtype->is_real_question_type()) {
f9b0500f 1697 print_qtype_to_add_option($qtype);
b974f947 1698 } else {
f9b0500f 1699 $fakeqtypes[] = $qtype;
b974f947 1700 }
1701 }
1702 echo "</div>\n";
1703 echo '<div class="fakeqtypes">' . "\n";
a13d4fbd 1704 foreach ($fakeqtypes as $qtype) {
f9b0500f 1705 print_qtype_to_add_option($qtype);
cd120b23 1706 }
1707 echo "</div>\n";
b974f947 1708 echo "</div>\n";
cd120b23 1709 echo '<div class="submitbuttons">' . "\n";
1710 echo '<input type="submit" value="' . get_string('next') . '" id="chooseqtype_submit" />' . "\n";
1711 echo '<input type="submit" id="chooseqtypecancel" name="addcancel" value="' . get_string('cancel') . '" />' . "\n";
1712 echo "</div></form>\n";
1713 echo "</div>\n";
a13d4fbd 1714 $PAGE->requires->js_init_call('qtype_chooser.init', array('chooseqtype'));
cd120b23 1715}
1716
1717/**
1718 * Private function used by the preceding one.
1719 * @param $qtype the question type.
cd120b23 1720 */
f9b0500f 1721function print_qtype_to_add_option($qtype) {
cd120b23 1722 echo '<div class="qtypeoption">' . "\n";
f9b0500f
TH
1723 echo '<label for="qtype_' . $qtype->name() . '">';
1724 echo '<input type="radio" name="qtype" id="qtype_' . $qtype->name() . '" value="' . $qtype->name() . '" />';
7cf3af55 1725 echo '<span class="qtypename">';
0ff4bd08 1726 $fakequestion = new stdClass();
f9b0500f 1727 $fakequestion->qtype = $qtype->name();
cd120b23 1728 print_question_icon($fakequestion);
f9b0500f
TH
1729 echo $qtype->menu_name() . '</span><span class="qtypesummary">' .
1730 get_string($qtype->name() . 'summary', 'qtype_' . $qtype->name());
cd120b23 1731 echo "</span></label>\n";
1732 echo "</div>\n";
1733}
1734
1735/**
1736 * Print a button for creating a new question. This will open question/addquestion.php,
1737 * which in turn goes to question/question.php before getting back to $params['returnurl']
1738 * (by default the question bank screen).
1739 *
1740 * @param integer $categoryid The id of the category that the new question should be added to.
1741 * @param array $params Other paramters to add to the URL. You need either $params['cmid'] or
1742 * $params['courseid'], and you should probably set $params['returnurl']
1743 * @param string $caption the text to display on the button.
1744 * @param string $tooltip a tooltip to add to the button (optional).
1745 * @param boolean $disabled if true, the button will be disabled.
1746 */
1747function create_new_question_button($categoryid, $params, $caption, $tooltip = '', $disabled = false) {
fef8f84e 1748 global $CFG, $PAGE, $OUTPUT;
cd120b23 1749 static $choiceformprinted = false;
1750 $params['category'] = $categoryid;
a6855934 1751 $url = new moodle_url('/question/addquestion.php', $params);
5c2ed7e2 1752 echo $OUTPUT->single_button($url, $caption, 'get', array('disabled'=>$disabled, 'title'=>$tooltip));
a941387a 1753
f44b10ed
PS
1754 $PAGE->requires->yui2_lib('dragdrop');
1755 $PAGE->requires->yui2_lib('container');
cd120b23 1756 if (!$choiceformprinted) {
1757 echo '<div id="qtypechoicecontainer">';
1758 print_choose_qtype_to_add_form(array());
1759 echo "</div>\n";
1760 $choiceformprinted = true;
1761 }
1762}
1763
aeb15530 1764