weekly release 2.4dev
[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));
271e6dec 120 require_capability('moodle/question:managecategory', get_context_instance_by_id($contextid));
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
137 /**
138 * Constructor.
139 * @param $qbank the question_bank_view we are helping to render.
140 */
141 public function __construct(question_bank_view $qbank) {
142 $this->qbank = $qbank;
143 $this->init();
144 }
145
146 /**
147 * A chance for subclasses to initialise themselves, for example to load lang strings,
148 * without having to override the constructor.
149 */
150 protected function init() {
151 }
46795afc 152
b7a9dc51 153 public function is_extra_row() {
154 return false;
155 }
156
46795afc 157 /**
158 * Output the column header cell.
46795afc 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 */
c7df5006 195 protected abstract 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 */
c7df5006 279 public abstract 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 */
c7df5006 293 protected abstract function display_content($question, $rowclasses);
46795afc 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.
f7970e3c 344 * @param bool $reverse whether the normal direction should be reversed.
46795afc 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
f7970e3c 378
46795afc 379/**
380 * A column with a checkbox for each question with name q{questionid}.
f7970e3c
TH
381 *
382 * @copyright 2009 Tim Hunt
383 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
46795afc 384 */
385class question_bank_checkbox_column extends question_bank_column_base {
386 protected $strselect;
2d1e69d3 387 protected $firstrow = true;
46795afc 388
5bd22790 389 public function init() {
5e8a85aa 390 $this->strselect = get_string('select');
46795afc 391 }
392
babdcb40 393 public function get_name() {
46795afc 394 return 'checkbox';
395 }
396
5bd22790 397 protected function get_title() {
bfb1691d 398 return '<input type="checkbox" disabled="disabled" id="qbheadercheckbox" />';
5bd22790 399 }
400
0ff5afdf 401 protected function get_title_tip() {
402 return get_string('selectquestionsforbulk', 'question');
403 }
404
46795afc 405 protected function display_content($question, $rowclasses) {
cf615522 406 global $PAGE;
46795afc 407 echo '<input title="' . $this->strselect . '" type="checkbox" name="q' .
bfb1691d 408 $question->id . '" id="checkq' . $question->id . '" value="1"/>';
2d1e69d3 409 if ($this->firstrow) {
7b66b651
PS
410 $PAGE->requires->js('/question/qengine.js');
411 $module = array(
412 'name' => 'qbank',
413 'fullpath' => '/question/qbank.js',
414 'requires' => array('yui2-dom', 'yui2-event', 'yui2-container'),
415 'strings' => array(),
416 'async' => false,
417 );
418 $PAGE->requires->js_init_call('question_bank.init_checkbox_column', array(get_string('selectall'),
419 get_string('deselectall'), 'checkq' . $question->id), false, $module);
2d1e69d3 420 $this->firstrow = false;
421 }
46795afc 422 }
423
424 public function get_required_fields() {
425 return array('q.id');
426 }
427}
428
f7970e3c 429
46795afc 430/**
431 * A column type for the name of the question type.
f7970e3c
TH
432 *
433 * @copyright 2009 Tim Hunt
434 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
46795afc 435 */
436class question_bank_question_type_column extends question_bank_column_base {
babdcb40 437 public function get_name() {
46795afc 438 return 'qtype';
439 }
440
5bd22790 441 protected function get_title() {
442 return get_string('qtypeveryshort', 'question');
443 }
444
0ff5afdf 445 protected function get_title_tip() {
446 return get_string('questiontype', 'question');
447 }
448
46795afc 449 protected function display_content($question, $rowclasses) {
450 echo print_question_icon($question);
451 }
452
453 public function get_required_fields() {
454 return array('q.qtype');
455 }
456
457 public function is_sortable() {
5bd22790 458 return 'q.qtype';
46795afc 459 }
460}
461
f7970e3c 462
46795afc 463/**
464 * A column type for the name of the question name.
f7970e3c
TH
465 *
466 * @copyright 2009 Tim Hunt
467 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
46795afc 468 */
469class question_bank_question_name_column extends question_bank_column_base {
971c6fca 470 protected $checkboxespresent = null;
471
babdcb40 472 public function get_name() {
46795afc 473 return 'questionname';
474 }
475
5bd22790 476 protected function get_title() {
477 return get_string('question');
478 }
479
971c6fca 480 protected function label_for($question) {
481 if (is_null($this->checkboxespresent)) {
482 $this->checkboxespresent = $this->qbank->has_column('checkbox');
483 }
484 if ($this->checkboxespresent) {
485 return 'checkq' . $question->id;
486 } else {
487 return '';
488 }
489 }
490
46795afc 491 protected function display_content($question, $rowclasses) {
971c6fca 492 $labelfor = $this->label_for($question);
493 if ($labelfor) {
494 echo '<label for="' . $labelfor . '">';
495 }
46795afc 496 echo format_string($question->name);
971c6fca 497 if ($labelfor) {
498 echo '</label>';
499 }
46795afc 500 }
501
502 public function get_required_fields() {
971c6fca 503 return array('q.id', 'q.name');
46795afc 504 }
505
506 public function is_sortable() {
5bd22790 507 return 'q.name';
46795afc 508 }
509}
510
f7970e3c 511
46795afc 512/**
513 * A column type for the name of the question creator.
f7970e3c
TH
514 *
515 * @copyright 2009 Tim Hunt
516 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
46795afc 517 */
518class question_bank_creator_name_column extends question_bank_column_base {
babdcb40 519 public function get_name() {
46795afc 520 return 'creatorname';
521 }
522
5bd22790 523 protected function get_title() {
524 return get_string('createdby', 'question');
525 }
526
46795afc 527 protected function display_content($question, $rowclasses) {
528 if (!empty($question->creatorfirstname) && !empty($question->creatorlastname)) {
0ff4bd08 529 $u = new stdClass();
46795afc 530 $u->firstname = $question->creatorfirstname;
531 $u->lastname = $question->creatorlastname;
532 echo fullname($u);
533 }
534 }
535
536 public function get_extra_joins() {
537 return array('uc' => 'LEFT JOIN {user} uc ON uc.id = q.createdby');
538 }
539
540 public function get_required_fields() {
541 return array('uc.firstname AS creatorfirstname', 'uc.lastname AS creatorlastname');
542 }
543
544 public function is_sortable() {
5bd22790 545 return array(
546 'firstname' => array('field' => 'uc.firstname', 'title' => get_string('firstname')),
547 'lastname' => array('field' => 'uc.lastname', 'title' => get_string('lastname')),
548 );
46795afc 549 }
550}
551
f7970e3c 552
46795afc 553/**
554 * A column type for the name of the question last modifier.
f7970e3c
TH
555 *
556 * @copyright 2009 Tim Hunt
557 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
46795afc 558 */
559class question_bank_modifier_name_column extends question_bank_column_base {
babdcb40 560 public function get_name() {
46795afc 561 return 'modifiername';
562 }
563
5bd22790 564 protected function get_title() {
565 return get_string('lastmodifiedby', 'question');
566 }
567
46795afc 568 protected function display_content($question, $rowclasses) {
569 if (!empty($question->modifierfirstname) && !empty($question->modifierlastname)) {
0ff4bd08 570 $u = new stdClass();
46795afc 571 $u->firstname = $question->modifierfirstname;
572 $u->lastname = $question->modifierlastname;
573 echo fullname($u);
574 }
575 }
576
577 public function get_extra_joins() {
578 return array('um' => 'LEFT JOIN {user} um ON um.id = q.modifiedby');
579 }
580
581 public function get_required_fields() {
582 return array('um.firstname AS modifierfirstname', 'um.lastname AS modifierlastname');
583 }
584
585 public function is_sortable() {
5bd22790 586 return array(
587 'firstname' => array('field' => 'um.firstname', 'title' => get_string('firstname')),
588 'lastname' => array('field' => 'um.lastname', 'title' => get_string('lastname')),
589 );
46795afc 590 }
591}
592
f7970e3c 593
46795afc 594/**
595 * A base class for actions that are an icon that lets you manipulate the question in some way.
f7970e3c
TH
596 *
597 * @copyright 2009 Tim Hunt
598 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
46795afc 599 */
600abstract class question_bank_action_column_base extends question_bank_column_base {
5bd22790 601
602 protected function get_title() {
603 return '&#160;';
604 }
605
b7a9dc51 606 public function get_extra_classes() {
607 return array('iconcol');
608 }
609
46795afc 610 protected function print_icon($icon, $title, $url) {
e63f88c9 611 global $OUTPUT;
46795afc 612 echo '<a title="' . $title . '" href="' . $url . '">
b5d0cafc 613 <img src="' . $OUTPUT->pix_url($icon) . '" class="iconsmall" alt="' . $title . '" /></a>';
46795afc 614 }
615
616 public function get_required_fields() {
51c5e605 617 // createdby is required for permission checks.
0eefca3b 618 return array('q.id', 'q.createdby');
46795afc 619 }
620}
621
f7970e3c
TH
622
623/**
624 * Base class for question bank columns that just contain an action icon.
625 *
626 * @copyright 2009 Tim Hunt
627 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
628 */
46795afc 629class question_bank_edit_action_column extends question_bank_action_column_base {
630 protected $stredit;
631 protected $strview;
46795afc 632
5bd22790 633 public function init() {
634 parent::init();
46795afc 635 $this->stredit = get_string('edit');
636 $this->strview = get_string('view');
637 }
638
babdcb40 639 public function get_name() {
46795afc 640 return 'editaction';
641 }
642
643 protected function display_content($question, $rowclasses) {
51c5e605 644 if (question_has_capability_on($question, 'edit')) {
a28c9253 645 $this->print_icon('t/edit', $this->stredit, $this->qbank->edit_question_url($question->id));
51c5e605 646 } else if (question_has_capability_on($question, 'view')) {
a28c9253 647 $this->print_icon('i/info', $this->strview, $this->qbank->edit_question_url($question->id));
46795afc 648 }
649 }
650}
651
f7970e3c
TH
652
653/**
654 * Question bank columns for the preview action icon.
655 *
656 * @copyright 2009 Tim Hunt
657 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
658 */
46795afc 659class question_bank_preview_action_column extends question_bank_action_column_base {
660 protected $strpreview;
46795afc 661
5bd22790 662 public function init() {
663 parent::init();
e4d1d5e0 664 $this->strpreview = get_string('preview');
46795afc 665 }
666
babdcb40 667 public function get_name() {
46795afc 668 return 'previewaction';
669 }
670
671 protected function display_content($question, $rowclasses) {
f2a1963c 672 global $OUTPUT;
46795afc 673 if (question_has_capability_on($question, 'use')) {
4bcc5118 674 // Build the icon.
000c278c 675 $image = $OUTPUT->pix_icon('t/preview', $this->strpreview);
80e7bb44 676
612106b3
TH
677 $link = $this->qbank->preview_question_url($question);
678 $action = new popup_action('click', $link, 'questionpreview',
679 question_preview_popup_params());
9bf16314
PS
680
681 echo $OUTPUT->action_link($link, $image, $action, array('title' => $this->strpreview));
46795afc 682 }
683 }
684
685 public function get_required_fields() {
686 return array('q.id');
687 }
688}
689
f7970e3c
TH
690
691/**
692 * Question bank columns for the move action icon.
693 *
694 * @copyright 2009 Tim Hunt
695 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
696 */
46795afc 697class question_bank_move_action_column extends question_bank_action_column_base {
698 protected $strmove;
46795afc 699
5bd22790 700 public function init() {
701 parent::init();
46795afc 702 $this->strmove = get_string('move');
703 }
704
babdcb40 705 public function get_name() {
706 return 'moveaction';
46795afc 707 }
708
709 protected function display_content($question, $rowclasses) {
710 if (question_has_capability_on($question, 'move')) {
a28c9253 711 $this->print_icon('t/move', $this->strmove, $this->qbank->move_question_url($question->id));
46795afc 712 }
713 }
714}
715
f7970e3c 716
46795afc 717/**
718 * action to delete (or hide) a question, or restore a previously hidden question.
f7970e3c
TH
719 *
720 * @copyright 2009 Tim Hunt
721 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
46795afc 722 */
723class question_bank_delete_action_column extends question_bank_action_column_base {
724 protected $strdelete;
725 protected $strrestore;
46795afc 726
5bd22790 727 public function init() {
728 parent::init();
46795afc 729 $this->strdelete = get_string('delete');
730 $this->strrestore = get_string('restore');
731 }
732
babdcb40 733 public function get_name() {
46795afc 734 return 'deleteaction';
735 }
736
737 protected function display_content($question, $rowclasses) {
738 if (question_has_capability_on($question, 'edit')) {
739 if ($question->hidden) {
8afba50b
PS
740 $url = new moodle_url($this->qbank->base_url(), array('unhide' => $question->id, 'sesskey'=>sesskey()));
741 $this->print_icon('t/restore', $this->strrestore, $url);
46795afc 742 } else {
8afba50b
PS
743 $url = new moodle_url($this->qbank->base_url(), array('deleteselected' => $question->id, 'q' . $question->id => 1, 'sesskey'=>sesskey()));
744 $this->print_icon('t/delete', $this->strdelete, $url);
46795afc 745 }
746 }
747 }
748
749 public function get_required_fields() {
750 return array('q.id', 'q.hidden');
751 }
752}
753
e4d1d5e0 754/**
755 * Base class for 'columns' that are actually displayed as a row following the main question row.
f7970e3c
TH
756 *
757 * @copyright 2009 Tim Hunt
758 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
e4d1d5e0 759 */
760abstract class question_bank_row_base extends question_bank_column_base {
b7a9dc51 761 public function is_extra_row() {
762 return true;
763 }
764
765 protected function display_start($question, $rowclasses) {
766 if ($rowclasses) {
767 echo '<tr class="' . $rowclasses . '">' . "\n";
768 } else {
769 echo "<tr>\n";
770 }
771 echo '<td colspan="' . $this->qbank->get_column_count() . '" class="' . $this->get_name() . '">';
772 }
773
774 protected function display_end($question, $rowclasses) {
775 echo "</td></tr>\n";
776 }
e4d1d5e0 777}
778
779/**
780 * A column type for the name of the question name.
f7970e3c
TH
781 *
782 * @copyright 2009 Tim Hunt
783 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
e4d1d5e0 784 */
785class question_bank_question_text_row extends question_bank_row_base {
b7a9dc51 786 protected $formatoptions;
787
788 protected function init() {
0ff4bd08 789 $this->formatoptions = new stdClass();
b7a9dc51 790 $this->formatoptions->noclean = true;
791 $this->formatoptions->para = false;
792 }
793
e4d1d5e0 794 public function get_name() {
795 return 'questiontext';
796 }
797
798 protected function get_title() {
799 return get_string('questiontext', 'question');
800 }
801
802 protected function display_content($question, $rowclasses) {
0019a9b7
TH
803 $text = question_rewrite_questiontext_preview_urls($question->questiontext,
804 $question->contextid, 'question', $question->id);
805 $text = format_text($text, $question->questiontextformat,
806 $this->formatoptions);
b7a9dc51 807 if ($text == '') {
808 $text = '&#160;';
809 }
810 echo $text;
e4d1d5e0 811 }
812
0019a9b7
TH
813 public function get_extra_joins() {
814 return array('qc' => 'JOIN {question_categories} qc ON qc.id = q.category');
815 }
816
e4d1d5e0 817 public function get_required_fields() {
0019a9b7 818 return array('q.id', 'q.questiontext', 'q.questiontextformat', 'qc.contextid');
e4d1d5e0 819 }
820}
821
4fbfd971 822/**
f4b879dd 823 * This class prints a view of the question bank, including
824 * + Some controls to allow users to to select what is displayed.
825 * + A list of questions as a table.
826 * + Further controls to do things with the questions.
827 *
828 * This class gives a basic view, and provides plenty of hooks where subclasses
829 * can override parts of the display.
830 *
831 * The list of questions presented as a table is generated by creating a list of
832 * question_bank_column objects, one for each 'column' to be displayed. These
833 * manage
834 * + outputting the contents of that column, given a $question object, but also
835 * + generating the right fragments of SQL to ensure the necessary data is present,
836 * and sorted in the right order.
837 * + outputting table headers.
f7970e3c
TH
838 *
839 * @copyright 2009 Tim Hunt
840 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4fbfd971 841 */
f4b879dd 842class question_bank_view {
e4d1d5e0 843 const MAX_SORTS = 3;
844
5bd22790 845 protected $baseurl;
846 protected $editquestionurl;
847 protected $quizorcourseid;
848 protected $contexts;
849 protected $cm;
971c6fca 850 protected $course;
b221dc6f 851 protected $knowncolumntypes;
852 protected $visiblecolumns;
b7a9dc51 853 protected $extrarows;
b221dc6f 854 protected $requiredcolumns;
855 protected $sort;
aa9c6ecf 856 protected $lastchangedid;
b221dc6f 857 protected $countsql;
858 protected $loadsql;
e4d1d5e0 859 protected $sqlparams;
5bd22790 860
612106b3
TH
861 /**
862 * Constructor
863 * @param question_edit_contexts $contexts
864 * @param moodle_url $pageurl
865 * @param object $course course settings
866 * @param object $cm (optional) activity settings.
867 */
971c6fca 868 public function __construct($contexts, $pageurl, $course, $cm = null) {
cf615522 869 global $CFG, $PAGE;
516cf3eb 870
5bd22790 871 $this->contexts = $contexts;
872 $this->baseurl = $pageurl;
971c6fca 873 $this->course = $course;
5bd22790 874 $this->cm = $cm;
875
876 if (!empty($cm) && $cm->modname == 'quiz') {
877 $this->quizorcourseid = '&amp;quizid=' . $cm->instance;
878 } else {
971c6fca 879 $this->quizorcourseid = '&amp;courseid=' .$this->course->id;
5bd22790 880 }
881
882 // Create the url of the new question page to forward to.
a530d4a9 883 $returnurl = $pageurl->out_as_local_url(false);
90c7912e
TH
884 $this->editquestionurl = new moodle_url('/question/question.php',
885 array('returnurl' => $returnurl));
5bd22790 886 if ($cm !== null){
887 $this->editquestionurl->param('cmid', $cm->id);
888 } else {
971c6fca 889 $this->editquestionurl->param('courseid', $this->course->id);
5bd22790 890 }
b221dc6f 891
aa9c6ecf 892 $this->lastchangedid = optional_param('lastchanged',0,PARAM_INT);
893
b221dc6f 894 $this->init_column_types();
971c6fca 895 $this->init_columns($this->wanted_columns());
b221dc6f 896 $this->init_sort();
897 }
898
971c6fca 899 protected function wanted_columns() {
1a9def7c
TH
900 $columns = array('checkbox', 'qtype', 'questionname', 'editaction',
901 'previewaction', 'moveaction', 'deleteaction', 'creatorname',
902 'modifiername');
b7a9dc51 903 if (optional_param('qbshowtext', false, PARAM_BOOL)) {
904 $columns[] = 'questiontext';
905 }
906 return $columns;
971c6fca 907 }
908
cd120b23 909 protected function known_field_types() {
971c6fca 910 return array(
b221dc6f 911 new question_bank_checkbox_column($this),
912 new question_bank_question_type_column($this),
913 new question_bank_question_name_column($this),
914 new question_bank_creator_name_column($this),
915 new question_bank_modifier_name_column($this),
916 new question_bank_edit_action_column($this),
917 new question_bank_preview_action_column($this),
918 new question_bank_move_action_column($this),
919 new question_bank_delete_action_column($this),
b7a9dc51 920 new question_bank_question_text_row($this),
b221dc6f 921 );
971c6fca 922 }
923
924 protected function init_column_types() {
b221dc6f 925 $this->knowncolumntypes = array();
cd120b23 926 foreach ($this->known_field_types() as $col) {
b221dc6f 927 $this->knowncolumntypes[$col->get_name()] = $col;
928 }
929 }
930
931 protected function init_columns($wanted) {
932 $this->visiblecolumns = array();
b7a9dc51 933 $this->extrarows = array();
b221dc6f 934 foreach ($wanted as $colname) {
935 if (!isset($this->knowncolumntypes[$colname])) {
936 throw new coding_exception('Unknown column type ' . $colname . ' requested in init columns.');
937 }
b7a9dc51 938 $column = $this->knowncolumntypes[$colname];
939 if ($column->is_extra_row()) {
940 $this->extrarows[$colname] = $column;
941 } else {
942 $this->visiblecolumns[$colname] = $column;
943 }
b221dc6f 944 }
b7a9dc51 945 $this->requiredcolumns = array_merge($this->visiblecolumns, $this->extrarows);
b221dc6f 946 }
947
e4d1d5e0 948 /**
949 * @param string $colname a column internal name.
f7970e3c 950 * @return bool is this column included in the output?
e4d1d5e0 951 */
952 public function has_column($colname) {
953 return isset($this->visiblecolumns[$colname]);
954 }
955
b7a9dc51 956 /**
f7970e3c 957 * @return int The number of columns in the table.
b7a9dc51 958 */
959 public function get_column_count() {
960 return count($this->visiblecolumns);
961 }
962
963 public function get_courseid() {
964 return $this->course->id;
965 }
966
b221dc6f 967 protected function init_sort() {
968 $this->init_sort_from_params();
969 if (empty($this->sort)) {
970 $this->sort = $this->default_sort();
971 }
972 }
973
974 /**
29ded2d6 975 * Deal with a sort name of the form columnname, or colname_subsort by
b221dc6f 976 * breaking it up, validating the bits that are presend, and returning them.
977 * If there is no subsort, then $subsort is returned as ''.
978 * @return array array($colname, $subsort).
979 */
980 protected function parse_subsort($sort) {
981 /// Do the parsing.
982 if (strpos($sort, '_') !== false) {
983 list($colname, $subsort) = explode('_', $sort, 2);
984 } else {
985 $colname = $sort;
986 $subsort = '';
987 }
988 /// Validate the column name.
989 if (!isset($this->knowncolumntypes[$colname]) || !$this->knowncolumntypes[$colname]->is_sortable()) {
e4d1d5e0 990 for ($i = 1; $i <= question_bank_view::MAX_SORTS; $i++) {
991 $this->baseurl->remove_params('qbs' . $i);
992 }
b221dc6f 993 throw new moodle_exception('unknownsortcolumn', '', $link = $this->baseurl->out(), $colname);
994 }
995 /// Validate the subsort, if present.
996 if ($subsort) {
997 $subsorts = $this->knowncolumntypes[$colname]->is_sortable();
998 if (!is_array($subsorts) || !isset($subsorts[$subsort])) {
999 throw new moodle_exception('unknownsortcolumn', '', $link = $this->baseurl->out(), $sort);
1000 }
1001 }
1002 return array($colname, $subsort);
1003 }
1004
1005 protected function init_sort_from_params() {
1006 $this->sort = array();
e4d1d5e0 1007 for ($i = 1; $i <= question_bank_view::MAX_SORTS; $i++) {
1008 if (!$sort = optional_param('qbs' . $i, '', PARAM_ALPHAEXT)) {
b221dc6f 1009 break;
1010 }
1011 // Work out the appropriate order.
1012 $order = 1;
1013 if ($sort[0] == '-') {
1014 $order = -1;
e4d1d5e0 1015 $sort = substr($sort, 1);
b221dc6f 1016 if (!$sort) {
1017 break;
1018 }
1019 }
1020 // Deal with subsorts.
1021 list($colname, $subsort) = $this->parse_subsort($sort);
1022 $this->requiredcolumns[$colname] = $this->knowncolumntypes[$colname];
e4d1d5e0 1023 $this->sort[$sort] = $order;
b221dc6f 1024 }
1025 }
1026
e4d1d5e0 1027 protected function sort_to_params($sorts) {
1028 $params = array();
1029 $i = 0;
1030 foreach ($sorts as $sort => $order) {
1031 $i += 1;
1032 if ($order < 0) {
1033 $sort = '-' . $sort;
1034 }
1035 $params['qbs' . $i] = $sort;
1036 }
1037 return $params;
1038 }
1039
b221dc6f 1040 protected function default_sort() {
ad3b37cf
TH
1041 $this->requiredcolumns['qtype'] = $this->knowncolumntypes['qtype'];
1042 $this->requiredcolumns['questionname'] = $this->knowncolumntypes['questionname'];
b221dc6f 1043 return array('qtype' => 1, 'questionname' => 1);
1044 }
1045
e4d1d5e0 1046 /**
1047 * @param $sort a column or column_subsort name.
f7970e3c 1048 * @return int the current sort order for this column -1, 0, 1
e4d1d5e0 1049 */
1050 public function get_primary_sort_order($sort) {
1051 $order = reset($this->sort);
1052 $primarysort = key($this->sort);
1053 if ($sort == $primarysort) {
1054 return $order;
1055 } else {
1056 return 0;
1057 }
1058 }
1059
1060 /**
1061 * Get a URL to redisplay the page with a new sort for the question bank.
1062 * @param string $sort the column, or column_subsort to sort on.
f7970e3c 1063 * @param bool $newsortreverse whether to sort in reverse order.
e4d1d5e0 1064 * @return string The new URL.
1065 */
1066 public function new_sort_url($sort, $newsortreverse) {
1067 if ($newsortreverse) {
1068 $order = -1;
1069 } else {
1070 $order = 1;
1071 }
1072 // Tricky code to add the new sort at the start, removing it from where it was before, if it was present.
1073 $newsort = array_reverse($this->sort);
1074 if (isset($newsort[$sort])) {
1075 unset($newsort[$sort]);
1076 }
1077 $newsort[$sort] = $order;
1078 $newsort = array_reverse($newsort);
1079 if (count($newsort) > question_bank_view::MAX_SORTS) {
1080 $newsort = array_slice($newsort, 0, question_bank_view::MAX_SORTS, true);
1081 }
b9bc2019 1082 return $this->baseurl->out(true, $this->sort_to_params($newsort));
e4d1d5e0 1083 }
1084
1085 protected function build_query_sql($category, $recurse, $showhidden) {
1086 global $DB;
1087
b221dc6f 1088 /// Get the required tables.
1089 $joins = array();
1090 foreach ($this->requiredcolumns as $column) {
1091 $extrajoins = $column->get_extra_joins();
1092 foreach ($extrajoins as $prefix => $join) {
1093 if (isset($joins[$prefix]) && $joins[$prefix] != $join) {
1094 throw new coding_exception('Join ' . $join . ' conflicts with previous join ' . $joins[$prefix]);
1095 }
1096 $joins[$prefix] = $join;
1097 }
1098 }
1099
1100 /// Get the required fields.
e4d1d5e0 1101 $fields = array('q.hidden', 'q.category');
b221dc6f 1102 foreach ($this->visiblecolumns as $column) {
e4d1d5e0 1103 $fields = array_merge($fields, $column->get_required_fields());
b221dc6f 1104 }
b7a9dc51 1105 foreach ($this->extrarows as $row) {
1106 $fields = array_merge($fields, $row->get_required_fields());
1107 }
b221dc6f 1108 $fields = array_unique($fields);
1109
1110 /// Build the order by clause.
1111 $sorts = array();
1112 foreach ($this->sort as $sort => $order) {
1113 list($colname, $subsort) = $this->parse_subsort($sort);
29ded2d6 1114 $sorts[] = $this->requiredcolumns[$colname]->sort_expression($order < 0, $subsort);
b221dc6f 1115 }
1116
e4d1d5e0 1117 /// Build the where clause.
0019a9b7 1118 $tests = array('q.parent = 0');
e4d1d5e0 1119
331bcf9a 1120 if (!$showhidden) {
0019a9b7 1121 $tests[] = 'q.hidden = 0';
e4d1d5e0 1122 }
1123
1124 if ($recurse) {
2daffca5 1125 $categoryids = question_categorylist($category->id);
e4d1d5e0 1126 } else {
1127 $categoryids = array($category->id);
1128 }
cf717dc2 1129 list($catidtest, $params) = $DB->get_in_or_equal($categoryids, SQL_PARAMS_NAMED, 'cat');
e4d1d5e0 1130 $tests[] = 'q.category ' . $catidtest;
1131 $this->sqlparams = $params;
1132
b221dc6f 1133 /// Build the SQL.
1134 $sql = ' FROM {question} q ' . implode(' ', $joins);
e4d1d5e0 1135 $sql .= ' WHERE ' . implode(' AND ', $tests);
b221dc6f 1136 $this->countsql = 'SELECT count(1)' . $sql;
e4d1d5e0 1137 $this->loadsql = 'SELECT ' . implode(', ', $fields) . $sql . ' ORDER BY ' . implode(', ', $sorts);
1138 $this->sqlparams = $params;
5bd22790 1139 }
1140
e4d1d5e0 1141 protected function get_question_count() {
1142 global $DB;
1143 return $DB->count_records_sql($this->countsql, $this->sqlparams);
1144 }
1145
1146 protected function load_page_questions($page, $perpage) {
1147 global $DB;
1148 $questions = $DB->get_recordset_sql($this->loadsql, $this->sqlparams, $page*$perpage, $perpage);
1149 if (!$questions->valid()) {
1150 /// No questions on this page. Reset to page 0.
1151 $questions = $DB->get_recordset_sql($this->loadsql, $this->sqlparams, 0, $perpage);
1152 }
1153 return $questions;
1154 }
1155
1156 public function base_url() {
1157 return $this->baseurl;
5bd22790 1158 }
1159
1160 public function edit_question_url($questionid) {
b9bc2019 1161 return $this->editquestionurl->out(true, array('id' => $questionid));
5bd22790 1162 }
1163
e4d1d5e0 1164 public function move_question_url($questionid) {
b9bc2019 1165 return $this->editquestionurl->out(true, array('id' => $questionid, 'movecontext' => 1));
e4d1d5e0 1166 }
1167
612106b3 1168 public function preview_question_url($question) {
56a4ae46
TH
1169 return question_preview_url($question->id, null, null, null, null,
1170 $this->contexts->lowest());
f4b879dd 1171 }
516cf3eb 1172
f4b879dd 1173 /**
1174 * Shows the question bank editing interface.
1175 *
1176 * The function also processes a number of actions:
1177 *
1178 * Actions affecting the question pool:
1179 * move Moves a question to a different category
1180 * deleteselected Deletes the selected questions from the category
1181 * Other actions:
1182 * category Chooses the category
1183 * displayoptions Sets display options
f4b879dd 1184 */
b72b4137
TH
1185 public function display($tabname, $page, $perpage, $cat,
1186 $recurse, $showhidden, $showquestiontext) {
723d610c 1187 global $PAGE, $OUTPUT;
f4b879dd 1188
5bd22790 1189 if ($this->process_actions_needing_ui()) {
5b5e5ab2 1190 return;
f4b879dd 1191 }
516cf3eb 1192
5b5e5ab2 1193 // Category selection form
723d610c 1194 echo $OUTPUT->heading(get_string('questionbank', 'question'), 2);
5b5e5ab2 1195
5bd22790 1196 $this->display_category_form($this->contexts->having_one_edit_tab_cap($tabname),
971c6fca 1197 $this->baseurl, $cat);
1198 $this->display_options($recurse, $showhidden, $showquestiontext);
1199
1200 if (!$category = $this->get_current_category($cat)) {
1201 return;
1202 }
1203 $this->print_category_info($category);
624cbc9c 1204
f4b879dd 1205 // continues with list of questions
b72b4137
TH
1206 $this->display_question_list($this->contexts->having_one_edit_tab_cap($tabname),
1207 $this->baseurl, $cat, $this->cm,
1208 $recurse, $page, $perpage, $showhidden, $showquestiontext,
5bd22790 1209 $this->contexts->having_cap('moodle/question:add'));
516cf3eb 1210 }
1211
971c6fca 1212 protected function print_choose_category_message($categoryandcontext) {
1213 echo "<p style=\"text-align:center;\"><b>";
0030db53 1214 print_string('selectcategoryabove', 'question');
971c6fca 1215 echo "</b></p>";
1216 }
1217
1218 protected function get_current_category($categoryandcontext) {
beb677cd 1219 global $DB, $OUTPUT;
971c6fca 1220 list($categoryid, $contextid) = explode(',', $categoryandcontext);
1221 if (!$categoryid) {
1222 $this->print_choose_category_message($categoryandcontext);
1223 return false;
1224 }
1225
1226 if (!$category = $DB->get_record('question_categories',
1227 array('id' => $categoryid, 'contextid' => $contextid))) {
beb677cd 1228 echo $OUTPUT->box_start('generalbox questionbank');
fef8f84e 1229 echo $OUTPUT->notification('Category not found!');
beb677cd 1230 echo $OUTPUT->box_end();
971c6fca 1231 return false;
1232 }
1233
1234 return $category;
1235 }
1236
1237 protected function print_category_info($category) {
0ff4bd08 1238 $formatoptions = new stdClass();
971c6fca 1239 $formatoptions->noclean = true;
367a75fa 1240 $formatoptions->overflowdiv = true;
971c6fca 1241 echo '<div class="boxaligncenter">';
22cebed5 1242 echo format_text($category->info, $category->infoformat, $formatoptions, $this->course->id);
971c6fca 1243 echo "</div>\n";
1244 }
1245
f4b879dd 1246 /**
1247 * prints a form to choose categories
1248 */
971c6fca 1249 protected function display_category_form($contexts, $pageurl, $current) {
68e90fcc 1250 global $CFG, $OUTPUT;
516cf3eb 1251
f4b879dd 1252 /// Get all the existing categories now
cd120b23 1253 echo '<div class="choosecategory">';
f4b879dd 1254 $catmenu = question_category_options($contexts, false, 0, true);
0fd3556d 1255
fa16dd3d 1256 $select = new single_select($this->baseurl, 'category', $catmenu, $current, null, 'catmenu');
68e90fcc 1257 $select->set_label(get_string('selectacategory', 'question'));
94fa6be4 1258 echo $OUTPUT->render($select);
cd120b23 1259 echo "</div>\n";
971c6fca 1260 }
f4b879dd 1261
92e6e128 1262 protected function display_options($recurse, $showhidden, $showquestiontext) {
f4b879dd 1263 echo '<form method="get" action="edit.php" id="displayoptions">';
1264 echo "<fieldset class='invisiblefieldset'>";
e20ad67d 1265 echo html_writer::input_hidden_params($this->baseurl, array('recurse', 'showhidden', 'qbshowtext'));
92e6e128
K
1266 $this->display_category_form_checkbox('recurse', $recurse, get_string('includesubcategories', 'question'));
1267 $this->display_category_form_checkbox('showhidden', $showhidden, get_string('showhidden', 'question'));
1268 $this->display_category_form_checkbox('qbshowtext', $showquestiontext, get_string('showquestiontext', 'question'));
f4b879dd 1269 echo '<noscript><div class="centerpara"><input type="submit" value="'. get_string('go') .'" />';
1270 echo '</div></noscript></fieldset></form>';
516cf3eb 1271 }
1272
f4b879dd 1273 /**
971c6fca 1274 * Print a single option checkbox. Used by the preceeding.
f4b879dd 1275 */
92e6e128 1276 protected function display_category_form_checkbox($name, $value, $label) {
f4b879dd 1277 echo '<div><input type="hidden" id="' . $name . '_off" name="' . $name . '" value="0" />';
1278 echo '<input type="checkbox" id="' . $name . '_on" name="' . $name . '" value="1"';
92e6e128 1279 if ($value) {
f4b879dd 1280 echo ' checked="checked"';
516cf3eb 1281 }
f4b879dd 1282 echo ' onchange="getElementById(\'displayoptions\').submit(); return true;" />';
b7a9dc51 1283 echo '<label for="' . $name . '_on">' . $label . '</label>';
1284 echo "</div>\n";
516cf3eb 1285 }
1286
e4d1d5e0 1287 protected function create_new_question_form($category, $canadd) {
cd120b23 1288 global $CFG;
e4d1d5e0 1289 echo '<div class="createnewquestion">';
1290 if ($canadd) {
cd120b23 1291 create_new_question_button($category->id, $this->editquestionurl->params(),
1292 get_string('createnewquestion', 'question'));
e4d1d5e0 1293 } else {
1294 print_string('nopermissionadd', 'question');
1295 }
1296 echo '</div>';
1297 }
1298
f4b879dd 1299 /**
1300 * Prints the table of questions in a category with interactions
1301 *
1302 * @param object $course The course object
1303 * @param int $categoryid The id of the question category to be displayed
1304 * @param int $cm The course module record if we are in the context of a particular module, 0 otherwise
1305 * @param int $recurse This is 1 if subcategories should be included, 0 otherwise
1306 * @param int $page The number of the page to be displayed
1307 * @param int $perpage Number of questions to show per page
f7970e3c
TH
1308 * @param bool $showhidden True if also hidden questions should be displayed
1309 * @param bool $showquestiontext whether the text of each question should be shown in the list
f4b879dd 1310 */
5bd22790 1311 protected function display_question_list($contexts, $pageurl, $categoryandcontext,
5b5e5ab2 1312 $cm = null, $recurse=1, $page=0, $perpage=100, $showhidden=false,
f4b879dd 1313 $showquestiontext = false, $addcontexts = array()) {
bda3e711 1314 global $CFG, $DB, $OUTPUT;
f4b879dd 1315
e4d1d5e0 1316 $category = $this->get_current_category($categoryandcontext);
f4b879dd 1317
0ff4bd08 1318 $cmoptions = new stdClass();
971c6fca 1319 $cmoptions->hasattempts = !empty($this->quizhasattempts);
1320
5e8a85aa 1321 $strselectall = get_string('selectall');
2daffca5 1322 $strselectnone = get_string('deselectall');
5e8a85aa 1323 $strdelete = get_string('delete');
5b5e5ab2 1324
e4d1d5e0 1325 list($categoryid, $contextid) = explode(',', $categoryandcontext);
f4b879dd 1326 $catcontext = get_context_instance_by_id($contextid);
e4d1d5e0 1327
f4b879dd 1328 $canadd = has_capability('moodle/question:add', $catcontext);
f4b879dd 1329 $caneditall =has_capability('moodle/question:editall', $catcontext);
1330 $canuseall =has_capability('moodle/question:useall', $catcontext);
1331 $canmoveall =has_capability('moodle/question:moveall', $catcontext);
1332
e4d1d5e0 1333 $this->create_new_question_form($category, $canadd);
f4b879dd 1334
e4d1d5e0 1335 $this->build_query_sql($category, $recurse, $showhidden);
1336 $totalnumber = $this->get_question_count();
1337 if ($totalnumber == 0) {
f4b879dd 1338 return;
271e6dec 1339 }
1340
e4d1d5e0 1341 $questions = $this->load_page_questions($page, $perpage);
5b5e5ab2 1342
1343 echo '<div class="categorypagingbarcontainer">';
d6d8b94c 1344 $pageing_url = new moodle_url('edit.php');
1345 $r = $pageing_url->params($pageurl->params());
929d7a83 1346 $pagingbar = new paging_bar($totalnumber, $page, $perpage, $pageing_url);
9c7886e7 1347 $pagingbar->pagevar = 'qpage';
929d7a83 1348 echo $OUTPUT->render($pagingbar);
5b5e5ab2 1349 echo '</div>';
f4b879dd 1350
1351 echo '<form method="post" action="edit.php">';
1352 echo '<fieldset class="invisiblefieldset" style="display: block;">';
1353 echo '<input type="hidden" name="sesskey" value="'.sesskey().'" />';
6ea66ff3 1354 echo html_writer::input_hidden_params($pageurl);
f4b879dd 1355
cd120b23 1356 echo '<div class="categoryquestionscontainer">';
e4d1d5e0 1357 $this->start_table();
b7a9dc51 1358 $rowcount = 0;
f4b879dd 1359 foreach ($questions as $question) {
b7a9dc51 1360 $this->print_table_row($question, $rowcount);
1361 $rowcount += 1;
271e6dec 1362 }
e4d1d5e0 1363 $this->end_table();
cd120b23 1364 echo "</div>\n";
86909ce0 1365
5b5e5ab2 1366 echo '<div class="categorypagingbarcontainer pagingbottom">';
929d7a83 1367 echo $OUTPUT->render($pagingbar);
f4b879dd 1368 if ($totalnumber > DEFAULT_QUESTIONS_PER_PAGE) {
1369 if ($perpage == DEFAULT_QUESTIONS_PER_PAGE) {
2902edb4 1370 $url = new moodle_url('edit.php', array_merge($pageurl->params(), array('qperpage'=>1000)));
8afba50b 1371 $showall = '<a href="'.$url.'">'.get_string('showall', 'moodle', $totalnumber).'</a>';
f4b879dd 1372 } else {
2902edb4 1373 $url = new moodle_url('edit.php', array_merge($pageurl->params(), array('qperpage'=>DEFAULT_QUESTIONS_PER_PAGE)));
8afba50b 1374 $showall = '<a href="'.$url.'">'.get_string('showperpage', 'moodle', DEFAULT_QUESTIONS_PER_PAGE).'</a>';
f4b879dd 1375 }
b0f4e4e4 1376 echo "<div class='paging'>$showall</div>";
86909ce0 1377 }
5b5e5ab2 1378 echo '</div>';
f4b879dd 1379
5b5e5ab2 1380 echo '<div class="modulespecificbuttonscontainer">';
1381 if ($caneditall || $canmoveall || $canuseall){
5e8a85aa 1382 echo '<strong>&nbsp;'.get_string('withselected', 'question').':</strong><br />';
f4b879dd 1383
1384 if (function_exists('module_specific_buttons')) {
971c6fca 1385 echo module_specific_buttons($this->cm->id,$cmoptions);
f4b879dd 1386 }
5b5e5ab2 1387
f4b879dd 1388 // print delete and move selected question
1389 if ($caneditall) {
5b5e5ab2 1390 echo '<input type="submit" name="deleteselected" value="' . $strdelete . "\" />\n";
f4b879dd 1391 }
5b5e5ab2 1392
f4b879dd 1393 if ($canmoveall && count($addcontexts)) {
2daffca5 1394 echo '<input type="submit" name="move" value="'.get_string('moveto', 'question')."\" />\n";
f4b879dd 1395 question_category_select_menu($addcontexts, false, 0, "$category->id,$category->contextid");
1396 }
1397
1398 if (function_exists('module_specific_controls') && $canuseall) {
971c6fca 1399 $modulespecific = module_specific_controls($totalnumber, $recurse, $category, $this->cm->id,$cmoptions);
5b5e5ab2 1400 if(!empty($modulespecific)){
1401 echo "<hr />$modulespecific";
1402 }
271e6dec 1403 }
1404 }
5b5e5ab2 1405 echo "</div>\n";
1406
f4b879dd 1407 echo '</fieldset>';
1408 echo "</form>\n";
1409 }
1410
e4d1d5e0 1411 protected function start_table() {
1412 echo '<table id="categoryquestions">' . "\n";
1413 echo "<thead>\n";
1414 $this->print_table_headers();
1415 echo "</thead>\n";
1416 echo "<tbody>\n";
1417 }
1418
1419 protected function end_table() {
1420 echo "</tbody>\n";
1421 echo "</table>\n";
1422 }
1423
1424 protected function print_table_headers() {
1425 echo "<tr>\n";
1426 foreach ($this->visiblecolumns as $column) {
1427 $column->display_header();
1428 }
1429 echo "</tr>\n";
1430 }
1431
b7a9dc51 1432 protected function get_row_classes($question, $rowcount) {
e4d1d5e0 1433 $classes = array();
1434 if ($question->hidden) {
1435 $classes[] = 'dimmed_text';
1436 }
aa9c6ecf 1437 if ($question->id == $this->lastchangedid) {
aa37f5e3 1438 $classes[] ='highlight';
aa9c6ecf 1439 }
e6208ec6 1440 $classes[] = 'r' . ($rowcount % 2);
e4d1d5e0 1441 return $classes;
1442 }
1443
b7a9dc51 1444 protected function print_table_row($question, $rowcount) {
1445 $rowclasses = implode(' ', $this->get_row_classes($question, $rowcount));
e4d1d5e0 1446 if ($rowclasses) {
1447 echo '<tr class="' . $rowclasses . '">' . "\n";
1448 } else {
1449 echo "<tr>\n";
1450 }
1451 foreach ($this->visiblecolumns as $column) {
1452 $column->display($question, $rowclasses);
1453 }
1454 echo "</tr>\n";
b7a9dc51 1455 foreach ($this->extrarows as $row) {
1456 $row->display($question, $rowclasses);
1457 }
f4b879dd 1458 }
1459
5bd22790 1460 public function process_actions() {
971c6fca 1461 global $CFG, $DB;
f4b879dd 1462 /// Now, check for commands on this page and modify variables as necessary
5d548d3e
TH
1463 if (optional_param('move', false, PARAM_BOOL) and confirm_sesskey()) {
1464 // Move selected questions to new category
f4b879dd 1465 $category = required_param('category', PARAM_SEQUENCE);
1466 list($tocategoryid, $contextid) = explode(',', $category);
1467 if (! $tocategory = $DB->get_record('question_categories', array('id' => $tocategoryid, 'contextid' => $contextid))) {
1468 print_error('cannotfindcate', 'question');
271e6dec 1469 }
f4b879dd 1470 $tocontext = get_context_instance_by_id($contextid);
1471 require_capability('moodle/question:add', $tocontext);
1472 $rawdata = (array) data_submitted();
1473 $questionids = array();
1474 foreach ($rawdata as $key => $value) { // Parse input for question ids
1475 if (preg_match('!^q([0-9]+)$!', $key, $matches)) {
1476 $key = $matches[1];
1477 $questionids[] = $key;
271e6dec 1478 }
1479 }
fe6ce234 1480 if ($questionids) {
f4b879dd 1481 list($usql, $params) = $DB->get_in_or_equal($questionids);
5d548d3e
TH
1482 $sql = "";
1483 $questions = $DB->get_records_sql("
1484 SELECT q.*, c.contextid
1485 FROM {question} q
1486 JOIN {question_categories} c ON c.id = q.category
1487 WHERE q.id $usql", $params);
f4b879dd 1488 foreach ($questions as $question){
f4b879dd 1489 question_require_capability_on($question, 'move');
86909ce0 1490 }
5d548d3e
TH
1491 question_move_questions_to_category($questionids, $tocategory->id);
1492 redirect($this->baseurl->out(false,
1493 array('category' => "$tocategoryid,$contextid")));
86909ce0 1494 }
1495 }
86909ce0 1496
f4b879dd 1497 if (optional_param('deleteselected', false, PARAM_BOOL)) { // delete selected questions from the category
1498 if (($confirm = optional_param('confirm', '', PARAM_ALPHANUM)) and confirm_sesskey()) { // teacher has already confirmed the action
622365d2 1499 $deleteselected = required_param('deleteselected', PARAM_RAW);
f4b879dd 1500 if ($confirm == md5($deleteselected)) {
1501 if ($questionlist = explode(',', $deleteselected)) {
1502 // for each question either hide it if it is in use or delete it
1503 foreach ($questionlist as $questionid) {
4454447d 1504 $questionid = (int)$questionid;
f4b879dd 1505 question_require_capability_on($questionid, 'edit');
d1b7e03d 1506 if (questions_in_use(array($questionid))) {
f685e830 1507 $DB->set_field('question', 'hidden', 1, array('id' => $questionid));
f4b879dd 1508 } else {
d1b7e03d 1509 question_delete_question($questionid);
86909ce0 1510 }
86909ce0 1511 }
1512 }
c9f15305 1513 redirect($this->baseurl);
f4b879dd 1514 } else {
1515 print_error('invalidconfirm', 'question');
86909ce0 1516 }
86909ce0 1517 }
86909ce0 1518 }
8e77884c 1519
f4b879dd 1520 // Unhide a question
1521 if(($unhide = optional_param('unhide', '', PARAM_INT)) and confirm_sesskey()) {
1522 question_require_capability_on($unhide, 'edit');
f685e830 1523 $DB->set_field('question', 'hidden', 0, array('id' => $unhide));
c9f15305 1524 redirect($this->baseurl);
271e6dec 1525 }
271e6dec 1526 }
5bd22790 1527
1528 public function process_actions_needing_ui() {
a941387a 1529 global $DB, $OUTPUT;
5bd22790 1530 if (optional_param('deleteselected', false, PARAM_BOOL)) {
1531 // make a list of all the questions that are selected
1532 $rawquestions = $_REQUEST; // This code is called by both POST forms and GET links, so cannot use data_submitted.
1533 $questionlist = ''; // comma separated list of ids of questions to be deleted
1534 $questionnames = ''; // string with names of questions separated by <br /> with
1535 // an asterix in front of those that are in use
1536 $inuse = false; // set to true if at least one of the questions is in use
1537 foreach ($rawquestions as $key => $value) { // Parse input for question ids
1538 if (preg_match('!^q([0-9]+)$!', $key, $matches)) {
1539 $key = $matches[1];
1540 $questionlist .= $key.',';
1541 question_require_capability_on($key, 'edit');
d1b7e03d 1542 if (questions_in_use(array($key))) {
5bd22790 1543 $questionnames .= '* ';
1544 $inuse = true;
1545 }
1546 $questionnames .= $DB->get_field('question', 'name', array('id' => $key)) . '<br />';
1547 }
1548 }
1549 if (!$questionlist) { // no questions were selected
c9f15305 1550 redirect($this->baseurl);
5bd22790 1551 }
1552 $questionlist = rtrim($questionlist, ',');
1553
1554 // Add an explanation about questions in use
1555 if ($inuse) {
5e8a85aa 1556 $questionnames .= '<br />'.get_string('questionsinuse', 'question');
5bd22790 1557 }
8afba50b
PS
1558 $baseurl = new moodle_url('edit.php', $this->baseurl->params());
1559 $deleteurl = new moodle_url($baseurl, array('deleteselected'=>$questionlist, 'confirm'=>md5($questionlist), 'sesskey'=>sesskey()));
aeb15530 1560
5e8a85aa 1561 echo $OUTPUT->confirm(get_string('deletequestionscheck', 'question', $questionnames), $deleteurl, $baseurl);
5bd22790 1562
1563 return true;
1564 }
1565 }
86909ce0 1566}
f4b879dd 1567
b72ff476 1568/**
1569 * Common setup for all pages for editing questions.
453b28d8 1570 * @param string $baseurl the name of the script calling this funciton. For examle 'qusetion/edit.php'.
271e6dec 1571 * @param string $edittab code for this edit tab
f7970e3c
TH
1572 * @param bool $requirecmid require cmid? default false
1573 * @param bool $requirecourseid require courseid, if cmid is not given? default true
271e6dec 1574 * @return array $thispageurl, $contexts, $cmid, $cm, $module, $pagevars
b72ff476 1575 */
453b28d8 1576function question_edit_setup($edittab, $baseurl, $requirecmid = false, $requirecourseid = true) {
56ed242b 1577 global $DB, $PAGE;
271e6dec 1578
453b28d8 1579 $thispageurl = new moodle_url($baseurl);
47ce714b 1580 $thispageurl->remove_all_params(); // We are going to explicity add back everything important - this avoids unwanted params from being retained.
b4a2e413 1581
b72ff476 1582 if ($requirecmid){
1583 $cmid =required_param('cmid', PARAM_INT);
1584 } else {
1585 $cmid = optional_param('cmid', 0, PARAM_INT);
1586 }
1587 if ($cmid){
271e6dec 1588 list($module, $cm) = get_module_from_cmid($cmid);
b72ff476 1589 $courseid = $cm->course;
1590 $thispageurl->params(compact('cmid'));
271e6dec 1591 require_login($courseid, false, $cm);
21c08c63 1592 $thiscontext = context_module::instance($cmid);
b72ff476 1593 } else {
1594 $module = null;
1595 $cm = null;
1596 if ($requirecourseid){
1597 $courseid = required_param('courseid', PARAM_INT);
1598 } else {
1599 $courseid = optional_param('courseid', 0, PARAM_INT);
1600 }
1601 if ($courseid){
1602 $thispageurl->params(compact('courseid'));
271e6dec 1603 require_login($courseid, false);
21c08c63 1604 $thiscontext = context_course::instance($courseid);
271e6dec 1605 } else {
1606 $thiscontext = null;
b72ff476 1607 }
1608 }
271e6dec 1609
1610 if ($thiscontext){
1611 $contexts = new question_edit_contexts($thiscontext);
1612 $contexts->require_one_edit_tab_cap($edittab);
1613
1614 } else {
1615 $contexts = null;
1616 }
1617
4bf1be35
TH
1618 $PAGE->set_pagelayout('admin');
1619
36e298bc 1620 $pagevars['qpage'] = optional_param('qpage', -1, PARAM_INT);
271e6dec 1621
7bc26c8f 1622 //pass 'cat' from page to page and when 'category' comes from a drop down menu
271e6dec 1623 //then we also reset the qpage so we go to page 1 of
7bc26c8f 1624 //a new cat.
f19ed874
TH
1625 $pagevars['cat'] = optional_param('cat', 0, PARAM_SEQUENCE); // if empty will be set up later
1626 if ($category = optional_param('category', 0, PARAM_SEQUENCE)) {
1627 if ($pagevars['cat'] != $category) { // is this a move to a new category?
a18fbcfb 1628 $pagevars['cat'] = $category;
1629 $pagevars['qpage'] = 0;
1630 }
7bc26c8f 1631 }
1632 if ($pagevars['cat']){
1633 $thispageurl->param('cat', $pagevars['cat']);
1634 }
f19ed874
TH
1635 if (strpos($baseurl, '/question/') === 0) {
1636 navigation_node::override_active_url($thispageurl);
1637 }
1638
b72ff476 1639 if ($pagevars['qpage'] > -1) {
1640 $thispageurl->param('qpage', $pagevars['qpage']);
1641 } else {
1642 $pagevars['qpage'] = 0;
1643 }
1644
36e298bc 1645 $pagevars['qperpage'] = optional_param('qperpage', -1, PARAM_INT);
b72ff476 1646 if ($pagevars['qperpage'] > -1) {
1647 $thispageurl->param('qperpage', $pagevars['qperpage']);
1648 } else {
1649 $pagevars['qperpage'] = DEFAULT_QUESTIONS_PER_PAGE;
1650 }
271e6dec 1651
b72b4137
TH
1652 for ($i = 1; $i <= question_bank_view::MAX_SORTS; $i++) {
1653 $param = 'qbs' . $i;
1654 if (!$sort = optional_param($param, '', PARAM_ALPHAEXT)) {
1655 break;
1656 }
1657 $thispageurl->param($param, $sort);
271e6dec 1658 }
36e298bc 1659
271e6dec 1660 $defaultcategory = question_make_default_categories($contexts->all());
1661
1662 $contextlistarr = array();
1663 foreach ($contexts->having_one_edit_tab_cap($edittab) as $context){
1664 $contextlistarr[] = "'$context->id'";
1665 }
1666 $contextlist = join($contextlistarr, ' ,');
1667 if (!empty($pagevars['cat'])){
1668 $catparts = explode(',', $pagevars['cat']);
e0736817 1669 if (!$catparts[0] || (false !== array_search($catparts[1], $contextlistarr)) ||
f34488b2 1670 !$DB->count_records_select("question_categories", "id = ? AND contextid = ?", array($catparts[0], $catparts[1]))) {
5e8a85aa 1671 print_error('invalidcategory', 'question');
271e6dec 1672 }
1673 } else {
1674 $category = $defaultcategory;
1675 $pagevars['cat'] = "$category->id,$category->contextid";
36e298bc 1676 }
1677
1678 if(($recurse = optional_param('recurse', -1, PARAM_BOOL)) != -1) {
1679 $pagevars['recurse'] = $recurse;
1680 $thispageurl->param('recurse', $recurse);
1681 } else {
1682 $pagevars['recurse'] = 1;
1683 }
271e6dec 1684
36e298bc 1685 if(($showhidden = optional_param('showhidden', -1, PARAM_BOOL)) != -1) {
1686 $pagevars['showhidden'] = $showhidden;
1687 $thispageurl->param('showhidden', $showhidden);
1688 } else {
1689 $pagevars['showhidden'] = 0;
1690 }
271e6dec 1691
e20ad67d
TH
1692 if(($showquestiontext = optional_param('qbshowtext', -1, PARAM_BOOL)) != -1) {
1693 $pagevars['qbshowtext'] = $showquestiontext;
1694 $thispageurl->param('qbshowtext', $showquestiontext);
36e298bc 1695 } else {
e20ad67d 1696 $pagevars['qbshowtext'] = 0;
36e298bc 1697 }
271e6dec 1698
986effb6 1699 //category list page
1700 $pagevars['cpage'] = optional_param('cpage', 1, PARAM_INT);
1701 if ($pagevars['cpage'] != 1){
1702 $thispageurl->param('cpage', $pagevars['cpage']);
1703 }
36e298bc 1704
271e6dec 1705 return array($thispageurl, $contexts, $cmid, $cm, $module, $pagevars);
1706}
271e6dec 1707
271e6dec 1708/**
1709 * Make sure user is logged in as required in this context.
1710 */
1711function require_login_in_context($contextorid = null){
042a8403 1712 global $DB, $CFG;
271e6dec 1713 if (!is_object($contextorid)){
1714 $context = get_context_instance_by_id($contextorid);
1715 } else {
1716 $context = $contextorid;
1717 }
1718 if ($context && ($context->contextlevel == CONTEXT_COURSE)) {
1719 require_login($context->instanceid);
1720 } else if ($context && ($context->contextlevel == CONTEXT_MODULE)) {
f34488b2 1721 if ($cm = $DB->get_record('course_modules',array('id' =>$context->instanceid))) {
1722 if (!$course = $DB->get_record('course', array('id' => $cm->course))) {
0be2c858 1723 print_error('invalidcourseid');
271e6dec 1724 }
1725 require_course_login($course, true, $cm);
1726
1727 } else {
0be2c858 1728 print_error('invalidcoursemodule');
271e6dec 1729 }
1730 } else if ($context && ($context->contextlevel == CONTEXT_SYSTEM)) {
1731 if (!empty($CFG->forcelogin)) {
1732 require_login();
1733 }
1734
1735 } else {
1736 require_login();
1737 }
b72ff476 1738}
cd120b23 1739
1740/**
1741 * Print a form to let the user choose which question type to add.
1742 * When the form is submitted, it goes to the question.php script.
1743 * @param $hiddenparams hidden parameters to add to the form, in addition to
75733895
TH
1744 * the qtype radio buttons.
1745 * @param $allowedqtypes optional list of qtypes that are allowed. If given, only
1746 * those qtypes will be shown. Example value array('description', 'multichoice').
cd120b23 1747 */
75733895 1748function print_choose_qtype_to_add_form($hiddenparams, array $allowedqtypes = null) {
f9b0500f 1749 global $CFG, $PAGE, $OUTPUT;
7b66b651 1750
cd120b23 1751 echo '<div id="chooseqtypehead" class="hd">' . "\n";
723d610c 1752 echo $OUTPUT->heading(get_string('chooseqtypetoadd', 'question'), 3);
cd120b23 1753 echo "</div>\n";
1754 echo '<div id="chooseqtype">' . "\n";
1755 echo '<form action="' . $CFG->wwwroot . '/question/question.php" method="get"><div id="qtypeformdiv">' . "\n";
1756 foreach ($hiddenparams as $name => $value) {
1757 echo '<input type="hidden" name="' . s($name) . '" value="' . s($value) . '" />' . "\n";
1758 }
1759 echo "</div>\n";
cd120b23 1760 echo '<div class="qtypes">' . "\n";
1761 echo '<div class="instruction">' . get_string('selectaqtypefordescription', 'question') . "</div>\n";
b974f947 1762 echo '<div class="realqtypes">' . "\n";
b974f947 1763 $fakeqtypes = array();
75733895
TH
1764 foreach (question_bank::get_creatable_qtypes() as $qtypename => $qtype) {
1765 if ($allowedqtypes && !in_array($qtypename, $allowedqtypes)) {
1766 continue;
1767 }
a13d4fbd 1768 if ($qtype->is_real_question_type()) {
f9b0500f 1769 print_qtype_to_add_option($qtype);
b974f947 1770 } else {
f9b0500f 1771 $fakeqtypes[] = $qtype;
b974f947 1772 }
1773 }
1774 echo "</div>\n";
1775 echo '<div class="fakeqtypes">' . "\n";
a13d4fbd 1776 foreach ($fakeqtypes as $qtype) {
f9b0500f 1777 print_qtype_to_add_option($qtype);
cd120b23 1778 }
1779 echo "</div>\n";
b974f947 1780 echo "</div>\n";
cd120b23 1781 echo '<div class="submitbuttons">' . "\n";
1782 echo '<input type="submit" value="' . get_string('next') . '" id="chooseqtype_submit" />' . "\n";
1783 echo '<input type="submit" id="chooseqtypecancel" name="addcancel" value="' . get_string('cancel') . '" />' . "\n";
1784 echo "</div></form>\n";
1785 echo "</div>\n";
7b66b651
PS
1786
1787 $PAGE->requires->js('/question/qengine.js');
1788 $module = array(
1789 'name' => 'qbank',
1790 'fullpath' => '/question/qbank.js',
1791 'requires' => array('yui2-dom', 'yui2-event', 'yui2-container'),
1792 'strings' => array(),
1793 'async' => false,
1794 );
1795 $PAGE->requires->js_init_call('qtype_chooser.init', array('chooseqtype'), false, $module);
cd120b23 1796}
1797
1798/**
1799 * Private function used by the preceding one.
0b94d6bf 1800 * @param question_type $qtype the question type.
cd120b23 1801 */
f9b0500f 1802function print_qtype_to_add_option($qtype) {
cd120b23 1803 echo '<div class="qtypeoption">' . "\n";
0b94d6bf
TH
1804 echo '<label for="' . $qtype->plugin_name() . '">';
1805 echo '<input type="radio" name="qtype" id="' . $qtype->plugin_name() .
1806 '" value="' . $qtype->name() . '" />';
7cf3af55 1807 echo '<span class="qtypename">';
0ff4bd08 1808 $fakequestion = new stdClass();
f9b0500f 1809 $fakequestion->qtype = $qtype->name();
5cc021a0 1810 echo print_question_icon($fakequestion);
0b94d6bf
TH
1811 echo $qtype->menu_name() . '</span><span class="qtypesummary">' .
1812 get_string('pluginnamesummary', $qtype->plugin_name());
cd120b23 1813 echo "</span></label>\n";
1814 echo "</div>\n";
1815}
1816
1817/**
1818 * Print a button for creating a new question. This will open question/addquestion.php,
1819 * which in turn goes to question/question.php before getting back to $params['returnurl']
1820 * (by default the question bank screen).
1821 *
f7970e3c 1822 * @param int $categoryid The id of the category that the new question should be added to.
cd120b23 1823 * @param array $params Other paramters to add to the URL. You need either $params['cmid'] or
1824 * $params['courseid'], and you should probably set $params['returnurl']
1825 * @param string $caption the text to display on the button.
1826 * @param string $tooltip a tooltip to add to the button (optional).
f7970e3c 1827 * @param bool $disabled if true, the button will be disabled.
cd120b23 1828 */
1829function create_new_question_button($categoryid, $params, $caption, $tooltip = '', $disabled = false) {
fef8f84e 1830 global $CFG, $PAGE, $OUTPUT;
cd120b23 1831 static $choiceformprinted = false;
1832 $params['category'] = $categoryid;
a6855934 1833 $url = new moodle_url('/question/addquestion.php', $params);
5c2ed7e2 1834 echo $OUTPUT->single_button($url, $caption, 'get', array('disabled'=>$disabled, 'title'=>$tooltip));
a941387a 1835
cd120b23 1836 if (!$choiceformprinted) {
1837 echo '<div id="qtypechoicecontainer">';
1838 print_choose_qtype_to_add_form(array());
1839 echo "</div>\n";
1840 $choiceformprinted = true;
1841 }
1842}
1843
aeb15530 1844