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