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