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