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