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