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