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