MDL-43734: Prevent purging of all user session cache
[moodle.git] / question / editlib.php
blob3f39887ba4369767022d87e60d2cea08d3b3b900
1 <?php
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.
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/>.
17 /**
18 * Functions used to show question editing interface
20 * @package moodlecore
21 * @subpackage questionbank
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
27 defined('MOODLE_INTERNAL') || die();
29 require_once($CFG->libdir . '/questionlib.php');
31 define('DEFAULT_QUESTIONS_PER_PAGE', 20);
33 function get_module_from_cmid($cmid) {
34 global $CFG, $DB;
35 if (!$cmrec = $DB->get_record_sql("SELECT cm.*, md.name as modname
36 FROM {course_modules} cm,
37 {modules} md
38 WHERE cm.id = ? AND
39 md.id = cm.module", array($cmid))){
40 print_error('invalidcoursemodule');
41 } elseif (!$modrec =$DB->get_record($cmrec->modname, array('id' => $cmrec->instance))) {
42 print_error('invalidcoursemodule');
44 $modrec->instance = $modrec->id;
45 $modrec->cmid = $cmrec->id;
46 $cmrec->name = $modrec->name;
48 return array($modrec, $cmrec);
50 /**
51 * Function to read all questions for category into big array
53 * @param int $category category number
54 * @param bool $noparent if true only questions with NO parent will be selected
55 * @param bool $recurse include subdirectories
56 * @param bool $export set true if this is called by questionbank export
58 function get_questions_category( $category, $noparent=false, $recurse=true, $export=true ) {
59 global $DB;
61 // Build sql bit for $noparent
62 $npsql = '';
63 if ($noparent) {
64 $npsql = " and parent='0' ";
67 // Get list of categories
68 if ($recurse) {
69 $categorylist = question_categorylist($category->id);
70 } else {
71 $categorylist = array($category->id);
74 // Get the list of questions for the category
75 list($usql, $params) = $DB->get_in_or_equal($categorylist);
76 $questions = $DB->get_records_select('question', "category $usql $npsql", $params, 'qtype, name');
78 // Iterate through questions, getting stuff we need
79 $qresults = array();
80 foreach($questions as $key => $question) {
81 $question->export_process = $export;
82 $qtype = question_bank::get_qtype($question->qtype, false);
83 if ($export && $qtype->name() == 'missingtype') {
84 // Unrecognised question type. Skip this question when exporting.
85 continue;
87 $qtype->get_question_options($question);
88 $qresults[] = $question;
91 return $qresults;
94 /**
95 * @param int $categoryid a category id.
96 * @return bool whether this is the only top-level category in a context.
98 function question_is_only_toplevel_category_in_context($categoryid) {
99 global $DB;
100 return 1 == $DB->count_records_sql("
101 SELECT count(*)
102 FROM {question_categories} c1,
103 {question_categories} c2
104 WHERE c2.id = ?
105 AND c1.contextid = c2.contextid
106 AND c1.parent = 0 AND c2.parent = 0", array($categoryid));
110 * Check whether this user is allowed to delete this category.
112 * @param int $todelete a category id.
114 function question_can_delete_cat($todelete) {
115 global $DB;
116 if (question_is_only_toplevel_category_in_context($todelete)) {
117 print_error('cannotdeletecate', 'question');
118 } else {
119 $contextid = $DB->get_field('question_categories', 'contextid', array('id' => $todelete));
120 require_capability('moodle/question:managecategory', context::instance_by_id($contextid));
126 * Base class for representing a column in a {@link question_bank_view}.
128 * @copyright 2009 Tim Hunt
129 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
131 abstract class question_bank_column_base {
133 * @var question_bank_view
135 protected $qbank;
137 /** @var bool determine whether the column is td or th. */
138 protected $isheading = false;
141 * Constructor.
142 * @param $qbank the question_bank_view we are helping to render.
144 public function __construct(question_bank_view $qbank) {
145 $this->qbank = $qbank;
146 $this->init();
150 * A chance for subclasses to initialise themselves, for example to load lang strings,
151 * without having to override the constructor.
153 protected function init() {
157 * Set the column as heading
159 public function set_as_heading() {
160 $this->isheading = true;
163 public function is_extra_row() {
164 return false;
168 * Output the column header cell.
170 public function display_header() {
171 echo '<th class="header ' . $this->get_classes() . '" scope="col">';
172 $sortable = $this->is_sortable();
173 $name = $this->get_name();
174 $title = $this->get_title();
175 $tip = $this->get_title_tip();
176 if (is_array($sortable)) {
177 if ($title) {
178 echo '<div class="title">' . $title . '</div>';
180 $links = array();
181 foreach ($sortable as $subsort => $details) {
182 $links[] = $this->make_sort_link($name . '_' . $subsort,
183 $details['title'], '', !empty($details['reverse']));
185 echo '<div class="sorters">' . implode(' / ', $links) . '</div>';
186 } else if ($sortable) {
187 echo $this->make_sort_link($name, $title, $tip);
188 } else {
189 if ($tip) {
190 echo '<span title="' . $tip . '">';
192 echo $title;
193 if ($tip) {
194 echo '</span>';
197 echo "</th>\n";
201 * Title for this column. Not used if is_sortable returns an array.
202 * @param object $question the row from the $question table, augmented with extra information.
203 * @param string $rowclasses CSS class names that should be applied to this row of output.
205 protected abstract function get_title();
208 * @return string a fuller version of the name. Use this when get_title() returns
209 * something very short, and you want a longer version as a tool tip.
211 protected function get_title_tip() {
212 return '';
216 * Get a link that changes the sort order, and indicates the current sort state.
217 * @param $name internal name used for this type of sorting.
218 * @param $currentsort the current sort order -1, 0, 1 for descending, none, ascending.
219 * @param $title the link text.
220 * @param $defaultreverse whether the default sort order for this column is descending, rather than ascending.
221 * @return string HTML fragment.
223 protected function make_sort_link($sort, $title, $tip, $defaultreverse = false) {
224 $currentsort = $this->qbank->get_primary_sort_order($sort);
225 $newsortreverse = $defaultreverse;
226 if ($currentsort) {
227 $newsortreverse = $currentsort > 0;
229 if (!$tip) {
230 $tip = $title;
232 if ($newsortreverse) {
233 $tip = get_string('sortbyxreverse', '', $tip);
234 } else {
235 $tip = get_string('sortbyx', '', $tip);
237 $link = '<a href="' . $this->qbank->new_sort_url($sort, $newsortreverse) . '" title="' . $tip . '">';
238 $link .= $title;
239 if ($currentsort) {
240 $link .= $this->get_sort_icon($currentsort < 0);
242 $link .= '</a>';
243 return $link;
247 * Get an icon representing the corrent sort state.
248 * @param $reverse sort is descending, not ascending.
249 * @return string HTML image tag.
251 protected function get_sort_icon($reverse) {
252 global $OUTPUT;
253 if ($reverse) {
254 return $OUTPUT->pix_icon('t/sort_desc', get_string('desc'), '', array('class' => 'iconsort'));
255 } else {
256 return $OUTPUT->pix_icon('t/sort_asc', get_string('asc'), '', array('class' => 'iconsort'));
261 * Output this column.
262 * @param object $question the row from the $question table, augmented with extra information.
263 * @param string $rowclasses CSS class names that should be applied to this row of output.
265 public function display($question, $rowclasses) {
266 $this->display_start($question, $rowclasses);
267 $this->display_content($question, $rowclasses);
268 $this->display_end($question, $rowclasses);
272 * Output the opening column tag. If it is set as heading, it will use <th> tag instead of <td>
274 * @param stdClass $question
275 * @param array $rowclasses
277 protected function display_start($question, $rowclasses) {
278 $tag = 'td';
279 $attr = array('class' => $this->get_classes());
280 if ($this->isheading) {
281 $tag = 'th';
282 $attr['scope'] = 'row';
284 echo html_writer::start_tag($tag, $attr);
288 * @return string the CSS classes to apply to every cell in this column.
290 protected function get_classes() {
291 $classes = $this->get_extra_classes();
292 $classes[] = $this->get_name();
293 return implode(' ', $classes);
297 * @param object $question the row from the $question table, augmented with extra information.
298 * @return string internal name for this column. Used as a CSS class name,
299 * and to store information about the current sort. Must match PARAM_ALPHA.
301 public abstract function get_name();
304 * @return array any extra class names you would like applied to every cell in this column.
306 public function get_extra_classes() {
307 return array();
311 * Output the contents of this column.
312 * @param object $question the row from the $question table, augmented with extra information.
313 * @param string $rowclasses CSS class names that should be applied to this row of output.
315 protected abstract function display_content($question, $rowclasses);
318 * Output the closing column tag
320 * @param object $question
321 * @param string $rowclasses
323 protected function display_end($question, $rowclasses) {
324 $tag = 'td';
325 if ($this->isheading) {
326 $tag = 'th';
328 echo html_writer::end_tag($tag);
332 * Return an array 'table_alias' => 'JOIN clause' to bring in any data that
333 * this column required.
335 * The return values for all the columns will be checked. It is OK if two
336 * columns join in the same table with the same alias and identical JOIN clauses.
337 * If to columns try to use the same alias with different joins, you get an error.
338 * The only table included by default is the question table, which is aliased to 'q'.
340 * It is importnat that your join simply adds additional data (or NULLs) to the
341 * existing rows of the query. It must not cause additional rows.
343 * @return array 'table_alias' => 'JOIN clause'
345 public function get_extra_joins() {
346 return array();
350 * @return array fields required. use table alias 'q' for the question table, or one of the
351 * ones from get_extra_joins. Every field requested must specify a table prefix.
353 public function get_required_fields() {
354 return array();
358 * Can this column be sorted on? You can return either:
359 * + false for no (the default),
360 * + a field name, if sorting this column corresponds to sorting on that datbase field.
361 * + an array of subnames to sort on as follows
362 * return array(
363 * 'firstname' => array('field' => 'uc.firstname', 'title' => get_string('firstname')),
364 * 'lastname' => array('field' => 'uc.lastname', 'field' => get_string('lastname')),
365 * );
366 * As well as field, and field, you can also add 'revers' => 1 if you want the default sort
367 * order to be DESC.
368 * @return mixed as above.
370 public function is_sortable() {
371 return false;
375 * Helper method for building sort clauses.
376 * @param bool $reverse whether the normal direction should be reversed.
377 * @param string $normaldir 'ASC' or 'DESC'
378 * @return string 'ASC' or 'DESC'
380 protected function sortorder($reverse) {
381 if ($reverse) {
382 return ' DESC';
383 } else {
384 return ' ASC';
389 * @param $reverse Whether to sort in the reverse of the default sort order.
390 * @param $subsort if is_sortable returns an array of subnames, then this will be
391 * one of those. Otherwise will be empty.
392 * @return string some SQL to go in the order by clause.
394 public function sort_expression($reverse, $subsort) {
395 $sortable = $this->is_sortable();
396 if (is_array($sortable)) {
397 if (array_key_exists($subsort, $sortable)) {
398 return $sortable[$subsort]['field'] . $this->sortorder($reverse, !empty($sortable[$subsort]['reverse']));
399 } else {
400 throw new coding_exception('Unexpected $subsort type: ' . $subsort);
402 } else if ($sortable) {
403 return $sortable . $this->sortorder($reverse);
404 } else {
405 throw new coding_exception('sort_expression called on a non-sortable column.');
412 * A column with a checkbox for each question with name q{questionid}.
414 * @copyright 2009 Tim Hunt
415 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
417 class question_bank_checkbox_column extends question_bank_column_base {
418 protected $strselect;
419 protected $firstrow = true;
421 public function init() {
422 $this->strselect = get_string('select');
425 public function get_name() {
426 return 'checkbox';
429 protected function get_title() {
430 return '<input type="checkbox" disabled="disabled" id="qbheadercheckbox" />';
433 protected function get_title_tip() {
434 return get_string('selectquestionsforbulk', 'question');
437 protected function display_content($question, $rowclasses) {
438 global $PAGE;
439 echo '<input title="' . $this->strselect . '" type="checkbox" name="q' .
440 $question->id . '" id="checkq' . $question->id . '" value="1"/>';
441 if ($this->firstrow) {
442 $PAGE->requires->js('/question/qengine.js');
443 $module = array(
444 'name' => 'qbank',
445 'fullpath' => '/question/qbank.js',
446 'requires' => array('yui2-dom', 'yui2-event', 'yui2-container'),
447 'strings' => array(),
448 'async' => false,
450 $PAGE->requires->js_init_call('question_bank.init_checkbox_column', array(get_string('selectall'),
451 get_string('deselectall'), 'checkq' . $question->id), false, $module);
452 $this->firstrow = false;
456 public function get_required_fields() {
457 return array('q.id');
463 * A column type for the name of the question type.
465 * @copyright 2009 Tim Hunt
466 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
468 class question_bank_question_type_column extends question_bank_column_base {
469 public function get_name() {
470 return 'qtype';
473 protected function get_title() {
474 return get_string('qtypeveryshort', 'question');
477 protected function get_title_tip() {
478 return get_string('questiontype', 'question');
481 protected function display_content($question, $rowclasses) {
482 echo print_question_icon($question);
485 public function get_required_fields() {
486 return array('q.qtype');
489 public function is_sortable() {
490 return 'q.qtype';
496 * A column type for the name of the question name.
498 * @copyright 2009 Tim Hunt
499 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
501 class question_bank_question_name_column extends question_bank_column_base {
502 protected $checkboxespresent = null;
504 public function get_name() {
505 return 'questionname';
508 protected function get_title() {
509 return get_string('question');
512 protected function label_for($question) {
513 if (is_null($this->checkboxespresent)) {
514 $this->checkboxespresent = $this->qbank->has_column('checkbox');
516 if ($this->checkboxespresent) {
517 return 'checkq' . $question->id;
518 } else {
519 return '';
523 protected function display_content($question, $rowclasses) {
524 $labelfor = $this->label_for($question);
525 if ($labelfor) {
526 echo '<label for="' . $labelfor . '">';
528 echo format_string($question->name);
529 if ($labelfor) {
530 echo '</label>';
534 public function get_required_fields() {
535 return array('q.id', 'q.name');
538 public function is_sortable() {
539 return 'q.name';
545 * A column type for the name of the question creator.
547 * @copyright 2009 Tim Hunt
548 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
550 class question_bank_creator_name_column extends question_bank_column_base {
551 public function get_name() {
552 return 'creatorname';
555 protected function get_title() {
556 return get_string('createdby', 'question');
559 protected function display_content($question, $rowclasses) {
560 if (!empty($question->creatorfirstname) && !empty($question->creatorlastname)) {
561 $u = new stdClass();
562 $u = username_load_fields_from_object($u, $question, 'creator');
563 echo fullname($u);
567 public function get_extra_joins() {
568 return array('uc' => 'LEFT JOIN {user} uc ON uc.id = q.createdby');
571 public function get_required_fields() {
572 $allnames = get_all_user_name_fields();
573 $requiredfields = array();
574 foreach ($allnames as $allname) {
575 $requiredfields[] = 'uc.' . $allname . ' AS creator' . $allname;
577 return $requiredfields;
580 public function is_sortable() {
581 return array(
582 'firstname' => array('field' => 'uc.firstname', 'title' => get_string('firstname')),
583 'lastname' => array('field' => 'uc.lastname', 'title' => get_string('lastname')),
590 * A column type for the name of the question last modifier.
592 * @copyright 2009 Tim Hunt
593 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
595 class question_bank_modifier_name_column extends question_bank_column_base {
596 public function get_name() {
597 return 'modifiername';
600 protected function get_title() {
601 return get_string('lastmodifiedby', 'question');
604 protected function display_content($question, $rowclasses) {
605 if (!empty($question->modifierfirstname) && !empty($question->modifierlastname)) {
606 $u = new stdClass();
607 $u = username_load_fields_from_object($u, $question, 'modifier');
608 echo fullname($u);
612 public function get_extra_joins() {
613 return array('um' => 'LEFT JOIN {user} um ON um.id = q.modifiedby');
616 public function get_required_fields() {
617 $allnames = get_all_user_name_fields();
618 $requiredfields = array();
619 foreach ($allnames as $allname) {
620 $requiredfields[] = 'um.' . $allname . ' AS modifier' . $allname;
622 return $requiredfields;
625 public function is_sortable() {
626 return array(
627 'firstname' => array('field' => 'um.firstname', 'title' => get_string('firstname')),
628 'lastname' => array('field' => 'um.lastname', 'title' => get_string('lastname')),
635 * A base class for actions that are an icon that lets you manipulate the question in some way.
637 * @copyright 2009 Tim Hunt
638 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
640 abstract class question_bank_action_column_base extends question_bank_column_base {
642 protected function get_title() {
643 return '&#160;';
646 public function get_extra_classes() {
647 return array('iconcol');
650 protected function print_icon($icon, $title, $url) {
651 global $OUTPUT;
652 echo '<a title="' . $title . '" href="' . $url . '">
653 <img src="' . $OUTPUT->pix_url($icon) . '" class="iconsmall" alt="' . $title . '" /></a>';
656 public function get_required_fields() {
657 // createdby is required for permission checks.
658 return array('q.id', 'q.createdby');
664 * Base class for question bank columns that just contain an action icon.
666 * @copyright 2009 Tim Hunt
667 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
669 class question_bank_edit_action_column extends question_bank_action_column_base {
670 protected $stredit;
671 protected $strview;
673 public function init() {
674 parent::init();
675 $this->stredit = get_string('edit');
676 $this->strview = get_string('view');
679 public function get_name() {
680 return 'editaction';
683 protected function display_content($question, $rowclasses) {
684 if (question_has_capability_on($question, 'edit')) {
685 $this->print_icon('t/edit', $this->stredit, $this->qbank->edit_question_url($question->id));
686 } else if (question_has_capability_on($question, 'view')) {
687 $this->print_icon('i/info', $this->strview, $this->qbank->edit_question_url($question->id));
694 * Question bank columns for the preview action icon.
696 * @copyright 2009 Tim Hunt
697 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
699 class question_bank_preview_action_column extends question_bank_action_column_base {
700 protected $strpreview;
702 public function init() {
703 parent::init();
704 $this->strpreview = get_string('preview');
707 public function get_name() {
708 return 'previewaction';
711 protected function display_content($question, $rowclasses) {
712 global $OUTPUT;
713 if (question_has_capability_on($question, 'use')) {
714 // Build the icon.
715 $image = $OUTPUT->pix_icon('t/preview', $this->strpreview, '', array('class' => 'iconsmall'));
717 $link = $this->qbank->preview_question_url($question);
718 $action = new popup_action('click', $link, 'questionpreview',
719 question_preview_popup_params());
721 echo $OUTPUT->action_link($link, $image, $action, array('title' => $this->strpreview));
725 public function get_required_fields() {
726 return array('q.id');
732 * Question bank columns for the move action icon.
734 * @copyright 2009 Tim Hunt
735 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
737 class question_bank_move_action_column extends question_bank_action_column_base {
738 protected $strmove;
740 public function init() {
741 parent::init();
742 $this->strmove = get_string('move');
745 public function get_name() {
746 return 'moveaction';
749 protected function display_content($question, $rowclasses) {
750 if (question_has_capability_on($question, 'move')) {
751 $this->print_icon('t/move', $this->strmove, $this->qbank->move_question_url($question->id));
758 * action to delete (or hide) a question, or restore a previously hidden question.
760 * @copyright 2009 Tim Hunt
761 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
763 class question_bank_delete_action_column extends question_bank_action_column_base {
764 protected $strdelete;
765 protected $strrestore;
767 public function init() {
768 parent::init();
769 $this->strdelete = get_string('delete');
770 $this->strrestore = get_string('restore');
773 public function get_name() {
774 return 'deleteaction';
777 protected function display_content($question, $rowclasses) {
778 if (question_has_capability_on($question, 'edit')) {
779 if ($question->hidden) {
780 $url = new moodle_url($this->qbank->base_url(), array('unhide' => $question->id, 'sesskey'=>sesskey()));
781 $this->print_icon('t/restore', $this->strrestore, $url);
782 } else {
783 $url = new moodle_url($this->qbank->base_url(), array('deleteselected' => $question->id, 'q' . $question->id => 1, 'sesskey'=>sesskey()));
784 $this->print_icon('t/delete', $this->strdelete, $url);
789 public function get_required_fields() {
790 return array('q.id', 'q.hidden');
795 * Base class for 'columns' that are actually displayed as a row following the main question row.
797 * @copyright 2009 Tim Hunt
798 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
800 abstract class question_bank_row_base extends question_bank_column_base {
801 public function is_extra_row() {
802 return true;
805 protected function display_start($question, $rowclasses) {
806 if ($rowclasses) {
807 echo '<tr class="' . $rowclasses . '">' . "\n";
808 } else {
809 echo "<tr>\n";
811 echo '<td colspan="' . $this->qbank->get_column_count() . '" class="' . $this->get_name() . '">';
814 protected function display_end($question, $rowclasses) {
815 echo "</td></tr>\n";
820 * A column type for the name of the question name.
822 * @copyright 2009 Tim Hunt
823 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
825 class question_bank_question_text_row extends question_bank_row_base {
826 protected $formatoptions;
828 protected function init() {
829 $this->formatoptions = new stdClass();
830 $this->formatoptions->noclean = true;
831 $this->formatoptions->para = false;
834 public function get_name() {
835 return 'questiontext';
838 protected function get_title() {
839 return get_string('questiontext', 'question');
842 protected function display_content($question, $rowclasses) {
843 $text = question_rewrite_question_preview_urls($question->questiontext, $question->id,
844 $question->contextid, 'question', 'questiontext', $question->id,
845 $question->contextid, 'core_question');
846 $text = format_text($text, $question->questiontextformat,
847 $this->formatoptions);
848 if ($text == '') {
849 $text = '&#160;';
851 echo $text;
854 public function get_extra_joins() {
855 return array('qc' => 'JOIN {question_categories} qc ON qc.id = q.category');
858 public function get_required_fields() {
859 return array('q.id', 'q.questiontext', 'q.questiontextformat', 'qc.contextid');
864 * This class prints a view of the question bank, including
865 * + Some controls to allow users to to select what is displayed.
866 * + A list of questions as a table.
867 * + Further controls to do things with the questions.
869 * This class gives a basic view, and provides plenty of hooks where subclasses
870 * can override parts of the display.
872 * The list of questions presented as a table is generated by creating a list of
873 * question_bank_column objects, one for each 'column' to be displayed. These
874 * manage
875 * + outputting the contents of that column, given a $question object, but also
876 * + generating the right fragments of SQL to ensure the necessary data is present,
877 * and sorted in the right order.
878 * + outputting table headers.
880 * @copyright 2009 Tim Hunt
881 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
883 class question_bank_view {
884 const MAX_SORTS = 3;
886 protected $baseurl;
887 protected $editquestionurl;
888 protected $quizorcourseid;
889 protected $contexts;
890 protected $cm;
891 protected $course;
892 protected $knowncolumntypes;
893 protected $visiblecolumns;
894 protected $extrarows;
895 protected $requiredcolumns;
896 protected $sort;
897 protected $lastchangedid;
898 protected $countsql;
899 protected $loadsql;
900 protected $sqlparams;
903 * Constructor
904 * @param question_edit_contexts $contexts
905 * @param moodle_url $pageurl
906 * @param object $course course settings
907 * @param object $cm (optional) activity settings.
909 public function __construct($contexts, $pageurl, $course, $cm = null) {
910 global $CFG, $PAGE;
912 $this->contexts = $contexts;
913 $this->baseurl = $pageurl;
914 $this->course = $course;
915 $this->cm = $cm;
917 if (!empty($cm) && $cm->modname == 'quiz') {
918 $this->quizorcourseid = '&amp;quizid=' . $cm->instance;
919 } else {
920 $this->quizorcourseid = '&amp;courseid=' .$this->course->id;
923 // Create the url of the new question page to forward to.
924 $returnurl = $pageurl->out_as_local_url(false);
925 $this->editquestionurl = new moodle_url('/question/question.php',
926 array('returnurl' => $returnurl));
927 if ($cm !== null){
928 $this->editquestionurl->param('cmid', $cm->id);
929 } else {
930 $this->editquestionurl->param('courseid', $this->course->id);
933 $this->lastchangedid = optional_param('lastchanged',0,PARAM_INT);
935 $this->init_column_types();
936 $this->init_columns($this->wanted_columns(), $this->heading_column());
937 $this->init_sort();
940 protected function wanted_columns() {
941 $columns = array('checkbox', 'qtype', 'questionname', 'editaction',
942 'previewaction', 'moveaction', 'deleteaction', 'creatorname',
943 'modifiername');
944 if (question_get_display_preference('qbshowtext', 0, PARAM_BOOL, new moodle_url(''))) {
945 $columns[] = 'questiontext';
947 return $columns;
951 * Specify the column heading
953 * @return string Column name for the heading
955 protected function heading_column() {
956 return 'questionname';
959 protected function known_field_types() {
960 return array(
961 new question_bank_checkbox_column($this),
962 new question_bank_question_type_column($this),
963 new question_bank_question_name_column($this),
964 new question_bank_creator_name_column($this),
965 new question_bank_modifier_name_column($this),
966 new question_bank_edit_action_column($this),
967 new question_bank_preview_action_column($this),
968 new question_bank_move_action_column($this),
969 new question_bank_delete_action_column($this),
970 new question_bank_question_text_row($this),
974 protected function init_column_types() {
975 $this->knowncolumntypes = array();
976 foreach ($this->known_field_types() as $col) {
977 $this->knowncolumntypes[$col->get_name()] = $col;
982 * Initializing table columns
984 * @param array $wanted Collection of column names
985 * @param string $heading The name of column that is set as heading
987 protected function init_columns($wanted, $heading = '') {
988 $this->visiblecolumns = array();
989 $this->extrarows = array();
990 foreach ($wanted as $colname) {
991 if (!isset($this->knowncolumntypes[$colname])) {
992 throw new coding_exception('Unknown column type ' . $colname . ' requested in init columns.');
994 $column = $this->knowncolumntypes[$colname];
995 if ($column->is_extra_row()) {
996 $this->extrarows[$colname] = $column;
997 } else {
998 $this->visiblecolumns[$colname] = $column;
1001 $this->requiredcolumns = array_merge($this->visiblecolumns, $this->extrarows);
1002 if (array_key_exists($heading, $this->requiredcolumns)) {
1003 $this->requiredcolumns[$heading]->set_as_heading();
1008 * @param string $colname a column internal name.
1009 * @return bool is this column included in the output?
1011 public function has_column($colname) {
1012 return isset($this->visiblecolumns[$colname]);
1016 * @return int The number of columns in the table.
1018 public function get_column_count() {
1019 return count($this->visiblecolumns);
1022 public function get_courseid() {
1023 return $this->course->id;
1026 protected function init_sort() {
1027 $this->init_sort_from_params();
1028 if (empty($this->sort)) {
1029 $this->sort = $this->default_sort();
1034 * Deal with a sort name of the form columnname, or colname_subsort by
1035 * breaking it up, validating the bits that are presend, and returning them.
1036 * If there is no subsort, then $subsort is returned as ''.
1037 * @return array array($colname, $subsort).
1039 protected function parse_subsort($sort) {
1040 /// Do the parsing.
1041 if (strpos($sort, '_') !== false) {
1042 list($colname, $subsort) = explode('_', $sort, 2);
1043 } else {
1044 $colname = $sort;
1045 $subsort = '';
1047 /// Validate the column name.
1048 if (!isset($this->knowncolumntypes[$colname]) || !$this->knowncolumntypes[$colname]->is_sortable()) {
1049 for ($i = 1; $i <= question_bank_view::MAX_SORTS; $i++) {
1050 $this->baseurl->remove_params('qbs' . $i);
1052 throw new moodle_exception('unknownsortcolumn', '', $link = $this->baseurl->out(), $colname);
1054 /// Validate the subsort, if present.
1055 if ($subsort) {
1056 $subsorts = $this->knowncolumntypes[$colname]->is_sortable();
1057 if (!is_array($subsorts) || !isset($subsorts[$subsort])) {
1058 throw new moodle_exception('unknownsortcolumn', '', $link = $this->baseurl->out(), $sort);
1061 return array($colname, $subsort);
1064 protected function init_sort_from_params() {
1065 $this->sort = array();
1066 for ($i = 1; $i <= question_bank_view::MAX_SORTS; $i++) {
1067 if (!$sort = optional_param('qbs' . $i, '', PARAM_ALPHAEXT)) {
1068 break;
1070 // Work out the appropriate order.
1071 $order = 1;
1072 if ($sort[0] == '-') {
1073 $order = -1;
1074 $sort = substr($sort, 1);
1075 if (!$sort) {
1076 break;
1079 // Deal with subsorts.
1080 list($colname, $subsort) = $this->parse_subsort($sort);
1081 $this->requiredcolumns[$colname] = $this->knowncolumntypes[$colname];
1082 $this->sort[$sort] = $order;
1086 protected function sort_to_params($sorts) {
1087 $params = array();
1088 $i = 0;
1089 foreach ($sorts as $sort => $order) {
1090 $i += 1;
1091 if ($order < 0) {
1092 $sort = '-' . $sort;
1094 $params['qbs' . $i] = $sort;
1096 return $params;
1099 protected function default_sort() {
1100 $this->requiredcolumns['qtype'] = $this->knowncolumntypes['qtype'];
1101 $this->requiredcolumns['questionname'] = $this->knowncolumntypes['questionname'];
1102 return array('qtype' => 1, 'questionname' => 1);
1106 * @param $sort a column or column_subsort name.
1107 * @return int the current sort order for this column -1, 0, 1
1109 public function get_primary_sort_order($sort) {
1110 $order = reset($this->sort);
1111 $primarysort = key($this->sort);
1112 if ($sort == $primarysort) {
1113 return $order;
1114 } else {
1115 return 0;
1120 * Get a URL to redisplay the page with a new sort for the question bank.
1121 * @param string $sort the column, or column_subsort to sort on.
1122 * @param bool $newsortreverse whether to sort in reverse order.
1123 * @return string The new URL.
1125 public function new_sort_url($sort, $newsortreverse) {
1126 if ($newsortreverse) {
1127 $order = -1;
1128 } else {
1129 $order = 1;
1131 // Tricky code to add the new sort at the start, removing it from where it was before, if it was present.
1132 $newsort = array_reverse($this->sort);
1133 if (isset($newsort[$sort])) {
1134 unset($newsort[$sort]);
1136 $newsort[$sort] = $order;
1137 $newsort = array_reverse($newsort);
1138 if (count($newsort) > question_bank_view::MAX_SORTS) {
1139 $newsort = array_slice($newsort, 0, question_bank_view::MAX_SORTS, true);
1141 return $this->baseurl->out(true, $this->sort_to_params($newsort));
1144 protected function build_query_sql($category, $recurse, $showhidden) {
1145 global $DB;
1147 /// Get the required tables.
1148 $joins = array();
1149 foreach ($this->requiredcolumns as $column) {
1150 $extrajoins = $column->get_extra_joins();
1151 foreach ($extrajoins as $prefix => $join) {
1152 if (isset($joins[$prefix]) && $joins[$prefix] != $join) {
1153 throw new coding_exception('Join ' . $join . ' conflicts with previous join ' . $joins[$prefix]);
1155 $joins[$prefix] = $join;
1159 /// Get the required fields.
1160 $fields = array('q.hidden', 'q.category');
1161 foreach ($this->visiblecolumns as $column) {
1162 $fields = array_merge($fields, $column->get_required_fields());
1164 foreach ($this->extrarows as $row) {
1165 $fields = array_merge($fields, $row->get_required_fields());
1167 $fields = array_unique($fields);
1169 /// Build the order by clause.
1170 $sorts = array();
1171 foreach ($this->sort as $sort => $order) {
1172 list($colname, $subsort) = $this->parse_subsort($sort);
1173 $sorts[] = $this->requiredcolumns[$colname]->sort_expression($order < 0, $subsort);
1176 /// Build the where clause.
1177 $tests = array('q.parent = 0');
1179 if (!$showhidden) {
1180 $tests[] = 'q.hidden = 0';
1183 if ($recurse) {
1184 $categoryids = question_categorylist($category->id);
1185 } else {
1186 $categoryids = array($category->id);
1188 list($catidtest, $params) = $DB->get_in_or_equal($categoryids, SQL_PARAMS_NAMED, 'cat');
1189 $tests[] = 'q.category ' . $catidtest;
1190 $this->sqlparams = $params;
1192 /// Build the SQL.
1193 $sql = ' FROM {question} q ' . implode(' ', $joins);
1194 $sql .= ' WHERE ' . implode(' AND ', $tests);
1195 $this->countsql = 'SELECT count(1)' . $sql;
1196 $this->loadsql = 'SELECT ' . implode(', ', $fields) . $sql . ' ORDER BY ' . implode(', ', $sorts);
1197 $this->sqlparams = $params;
1200 protected function get_question_count() {
1201 global $DB;
1202 return $DB->count_records_sql($this->countsql, $this->sqlparams);
1205 protected function load_page_questions($page, $perpage) {
1206 global $DB;
1207 $questions = $DB->get_recordset_sql($this->loadsql, $this->sqlparams, $page*$perpage, $perpage);
1208 if (!$questions->valid()) {
1209 /// No questions on this page. Reset to page 0.
1210 $questions = $DB->get_recordset_sql($this->loadsql, $this->sqlparams, 0, $perpage);
1212 return $questions;
1215 public function base_url() {
1216 return $this->baseurl;
1219 public function edit_question_url($questionid) {
1220 return $this->editquestionurl->out(true, array('id' => $questionid));
1223 public function move_question_url($questionid) {
1224 return $this->editquestionurl->out(true, array('id' => $questionid, 'movecontext' => 1));
1227 public function preview_question_url($question) {
1228 return question_preview_url($question->id, null, null, null, null,
1229 $this->contexts->lowest());
1233 * Shows the question bank editing interface.
1235 * The function also processes a number of actions:
1237 * Actions affecting the question pool:
1238 * move Moves a question to a different category
1239 * deleteselected Deletes the selected questions from the category
1240 * Other actions:
1241 * category Chooses the category
1242 * displayoptions Sets display options
1244 public function display($tabname, $page, $perpage, $cat,
1245 $recurse, $showhidden, $showquestiontext) {
1246 global $PAGE, $OUTPUT;
1248 if ($this->process_actions_needing_ui()) {
1249 return;
1252 // Category selection form
1253 echo $OUTPUT->heading(get_string('questionbank', 'question'), 2);
1255 $this->display_category_form($this->contexts->having_one_edit_tab_cap($tabname),
1256 $this->baseurl, $cat);
1257 $this->display_options($recurse, $showhidden, $showquestiontext);
1259 if (!$category = $this->get_current_category($cat)) {
1260 return;
1262 $this->print_category_info($category);
1264 // continues with list of questions
1265 $this->display_question_list($this->contexts->having_one_edit_tab_cap($tabname),
1266 $this->baseurl, $cat, $this->cm,
1267 $recurse, $page, $perpage, $showhidden, $showquestiontext,
1268 $this->contexts->having_cap('moodle/question:add'));
1271 protected function print_choose_category_message($categoryandcontext) {
1272 echo "<p style=\"text-align:center;\"><b>";
1273 print_string('selectcategoryabove', 'question');
1274 echo "</b></p>";
1277 protected function get_current_category($categoryandcontext) {
1278 global $DB, $OUTPUT;
1279 list($categoryid, $contextid) = explode(',', $categoryandcontext);
1280 if (!$categoryid) {
1281 $this->print_choose_category_message($categoryandcontext);
1282 return false;
1285 if (!$category = $DB->get_record('question_categories',
1286 array('id' => $categoryid, 'contextid' => $contextid))) {
1287 echo $OUTPUT->box_start('generalbox questionbank');
1288 echo $OUTPUT->notification('Category not found!');
1289 echo $OUTPUT->box_end();
1290 return false;
1293 return $category;
1296 protected function print_category_info($category) {
1297 $formatoptions = new stdClass();
1298 $formatoptions->noclean = true;
1299 $formatoptions->overflowdiv = true;
1300 echo '<div class="boxaligncenter">';
1301 echo format_text($category->info, $category->infoformat, $formatoptions, $this->course->id);
1302 echo "</div>\n";
1306 * prints a form to choose categories
1308 protected function display_category_form($contexts, $pageurl, $current) {
1309 global $CFG, $OUTPUT;
1311 /// Get all the existing categories now
1312 echo '<div class="choosecategory">';
1313 $catmenu = question_category_options($contexts, false, 0, true);
1315 $select = new single_select($this->baseurl, 'category', $catmenu, $current, null, 'catmenu');
1316 $select->set_label(get_string('selectacategory', 'question'));
1317 echo $OUTPUT->render($select);
1318 echo "</div>\n";
1321 protected function display_options($recurse, $showhidden, $showquestiontext) {
1322 echo '<form method="get" action="edit.php" id="displayoptions">';
1323 echo "<fieldset class='invisiblefieldset'>";
1324 echo html_writer::input_hidden_params($this->baseurl, array('recurse', 'showhidden', 'qbshowtext'));
1325 $this->display_category_form_checkbox('recurse', $recurse, get_string('includesubcategories', 'question'));
1326 $this->display_category_form_checkbox('showhidden', $showhidden, get_string('showhidden', 'question'));
1327 $this->display_category_form_checkbox('qbshowtext', $showquestiontext, get_string('showquestiontext', 'question'));
1328 echo '<noscript><div class="centerpara"><input type="submit" value="'. get_string('go') .'" />';
1329 echo '</div></noscript></fieldset></form>';
1333 * Print a single option checkbox. Used by the preceeding.
1335 protected function display_category_form_checkbox($name, $value, $label) {
1336 echo '<div><input type="hidden" id="' . $name . '_off" name="' . $name . '" value="0" />';
1337 echo '<input type="checkbox" id="' . $name . '_on" name="' . $name . '" value="1"';
1338 if ($value) {
1339 echo ' checked="checked"';
1341 echo ' onchange="getElementById(\'displayoptions\').submit(); return true;" />';
1342 echo '<label for="' . $name . '_on">' . $label . '</label>';
1343 echo "</div>\n";
1346 protected function create_new_question_form($category, $canadd) {
1347 global $CFG;
1348 echo '<div class="createnewquestion">';
1349 if ($canadd) {
1350 create_new_question_button($category->id, $this->editquestionurl->params(),
1351 get_string('createnewquestion', 'question'));
1352 } else {
1353 print_string('nopermissionadd', 'question');
1355 echo '</div>';
1359 * Prints the table of questions in a category with interactions
1361 * @param object $course The course object
1362 * @param int $categoryid The id of the question category to be displayed
1363 * @param int $cm The course module record if we are in the context of a particular module, 0 otherwise
1364 * @param int $recurse This is 1 if subcategories should be included, 0 otherwise
1365 * @param int $page The number of the page to be displayed
1366 * @param int $perpage Number of questions to show per page
1367 * @param bool $showhidden True if also hidden questions should be displayed
1368 * @param bool $showquestiontext whether the text of each question should be shown in the list
1370 protected function display_question_list($contexts, $pageurl, $categoryandcontext,
1371 $cm = null, $recurse=1, $page=0, $perpage=100, $showhidden=false,
1372 $showquestiontext = false, $addcontexts = array()) {
1373 global $CFG, $DB, $OUTPUT;
1375 $category = $this->get_current_category($categoryandcontext);
1377 $cmoptions = new stdClass();
1378 $cmoptions->hasattempts = !empty($this->quizhasattempts);
1380 $strselectall = get_string('selectall');
1381 $strselectnone = get_string('deselectall');
1382 $strdelete = get_string('delete');
1384 list($categoryid, $contextid) = explode(',', $categoryandcontext);
1385 $catcontext = context::instance_by_id($contextid);
1387 $canadd = has_capability('moodle/question:add', $catcontext);
1388 $caneditall =has_capability('moodle/question:editall', $catcontext);
1389 $canuseall =has_capability('moodle/question:useall', $catcontext);
1390 $canmoveall =has_capability('moodle/question:moveall', $catcontext);
1392 $this->create_new_question_form($category, $canadd);
1394 $this->build_query_sql($category, $recurse, $showhidden);
1395 $totalnumber = $this->get_question_count();
1396 if ($totalnumber == 0) {
1397 return;
1399 $questions = $this->load_page_questions($page, $perpage);
1401 echo '<div class="categorypagingbarcontainer">';
1402 $pageing_url = new moodle_url('edit.php');
1403 $r = $pageing_url->params($pageurl->params());
1404 $pagingbar = new paging_bar($totalnumber, $page, $perpage, $pageing_url);
1405 $pagingbar->pagevar = 'qpage';
1406 echo $OUTPUT->render($pagingbar);
1407 echo '</div>';
1409 echo '<form method="post" action="edit.php">';
1410 echo '<fieldset class="invisiblefieldset" style="display: block;">';
1411 echo '<input type="hidden" name="sesskey" value="'.sesskey().'" />';
1412 echo html_writer::input_hidden_params($pageurl);
1414 echo '<div class="categoryquestionscontainer">';
1415 $this->start_table();
1416 $rowcount = 0;
1417 foreach ($questions as $question) {
1418 $this->print_table_row($question, $rowcount);
1419 $rowcount += 1;
1421 $this->end_table();
1422 echo "</div>\n";
1424 echo '<div class="categorypagingbarcontainer pagingbottom">';
1425 echo $OUTPUT->render($pagingbar);
1426 if ($totalnumber > DEFAULT_QUESTIONS_PER_PAGE) {
1427 if ($perpage == DEFAULT_QUESTIONS_PER_PAGE) {
1428 $url = new moodle_url('edit.php', array_merge($pageurl->params(), array('qperpage'=>1000)));
1429 $showall = '<a href="'.$url.'">'.get_string('showall', 'moodle', $totalnumber).'</a>';
1430 } else {
1431 $url = new moodle_url('edit.php', array_merge($pageurl->params(), array('qperpage'=>DEFAULT_QUESTIONS_PER_PAGE)));
1432 $showall = '<a href="'.$url.'">'.get_string('showperpage', 'moodle', DEFAULT_QUESTIONS_PER_PAGE).'</a>';
1434 echo "<div class='paging'>$showall</div>";
1436 echo '</div>';
1438 echo '<div class="modulespecificbuttonscontainer">';
1439 if ($caneditall || $canmoveall || $canuseall){
1440 echo '<strong>&nbsp;'.get_string('withselected', 'question').':</strong><br />';
1442 if (function_exists('module_specific_buttons')) {
1443 echo module_specific_buttons($this->cm->id,$cmoptions);
1446 // print delete and move selected question
1447 if ($caneditall) {
1448 echo '<input type="submit" name="deleteselected" value="' . $strdelete . "\" />\n";
1451 if ($canmoveall && count($addcontexts)) {
1452 echo '<input type="submit" name="move" value="'.get_string('moveto', 'question')."\" />\n";
1453 question_category_select_menu($addcontexts, false, 0, "$category->id,$category->contextid");
1456 if (function_exists('module_specific_controls') && $canuseall) {
1457 $modulespecific = module_specific_controls($totalnumber, $recurse, $category, $this->cm->id,$cmoptions);
1458 if(!empty($modulespecific)){
1459 echo "<hr />$modulespecific";
1463 echo "</div>\n";
1465 echo '</fieldset>';
1466 echo "</form>\n";
1469 protected function start_table() {
1470 echo '<table id="categoryquestions">' . "\n";
1471 echo "<thead>\n";
1472 $this->print_table_headers();
1473 echo "</thead>\n";
1474 echo "<tbody>\n";
1477 protected function end_table() {
1478 echo "</tbody>\n";
1479 echo "</table>\n";
1482 protected function print_table_headers() {
1483 echo "<tr>\n";
1484 foreach ($this->visiblecolumns as $column) {
1485 $column->display_header();
1487 echo "</tr>\n";
1490 protected function get_row_classes($question, $rowcount) {
1491 $classes = array();
1492 if ($question->hidden) {
1493 $classes[] = 'dimmed_text';
1495 if ($question->id == $this->lastchangedid) {
1496 $classes[] ='highlight';
1498 $classes[] = 'r' . ($rowcount % 2);
1499 return $classes;
1502 protected function print_table_row($question, $rowcount) {
1503 $rowclasses = implode(' ', $this->get_row_classes($question, $rowcount));
1504 if ($rowclasses) {
1505 echo '<tr class="' . $rowclasses . '">' . "\n";
1506 } else {
1507 echo "<tr>\n";
1509 foreach ($this->visiblecolumns as $column) {
1510 $column->display($question, $rowclasses);
1512 echo "</tr>\n";
1513 foreach ($this->extrarows as $row) {
1514 $row->display($question, $rowclasses);
1518 public function process_actions() {
1519 global $CFG, $DB;
1520 /// Now, check for commands on this page and modify variables as necessary
1521 if (optional_param('move', false, PARAM_BOOL) and confirm_sesskey()) {
1522 // Move selected questions to new category
1523 $category = required_param('category', PARAM_SEQUENCE);
1524 list($tocategoryid, $contextid) = explode(',', $category);
1525 if (! $tocategory = $DB->get_record('question_categories', array('id' => $tocategoryid, 'contextid' => $contextid))) {
1526 print_error('cannotfindcate', 'question');
1528 $tocontext = context::instance_by_id($contextid);
1529 require_capability('moodle/question:add', $tocontext);
1530 $rawdata = (array) data_submitted();
1531 $questionids = array();
1532 foreach ($rawdata as $key => $value) { // Parse input for question ids
1533 if (preg_match('!^q([0-9]+)$!', $key, $matches)) {
1534 $key = $matches[1];
1535 $questionids[] = $key;
1538 if ($questionids) {
1539 list($usql, $params) = $DB->get_in_or_equal($questionids);
1540 $sql = "";
1541 $questions = $DB->get_records_sql("
1542 SELECT q.*, c.contextid
1543 FROM {question} q
1544 JOIN {question_categories} c ON c.id = q.category
1545 WHERE q.id $usql", $params);
1546 foreach ($questions as $question){
1547 question_require_capability_on($question, 'move');
1549 question_move_questions_to_category($questionids, $tocategory->id);
1550 redirect($this->baseurl->out(false,
1551 array('category' => "$tocategoryid,$contextid")));
1555 if (optional_param('deleteselected', false, PARAM_BOOL)) { // delete selected questions from the category
1556 if (($confirm = optional_param('confirm', '', PARAM_ALPHANUM)) and confirm_sesskey()) { // teacher has already confirmed the action
1557 $deleteselected = required_param('deleteselected', PARAM_RAW);
1558 if ($confirm == md5($deleteselected)) {
1559 if ($questionlist = explode(',', $deleteselected)) {
1560 // for each question either hide it if it is in use or delete it
1561 foreach ($questionlist as $questionid) {
1562 $questionid = (int)$questionid;
1563 question_require_capability_on($questionid, 'edit');
1564 if (questions_in_use(array($questionid))) {
1565 $DB->set_field('question', 'hidden', 1, array('id' => $questionid));
1566 } else {
1567 question_delete_question($questionid);
1571 redirect($this->baseurl);
1572 } else {
1573 print_error('invalidconfirm', 'question');
1578 // Unhide a question
1579 if(($unhide = optional_param('unhide', '', PARAM_INT)) and confirm_sesskey()) {
1580 question_require_capability_on($unhide, 'edit');
1581 $DB->set_field('question', 'hidden', 0, array('id' => $unhide));
1583 // Purge these questions from the cache.
1584 question_bank::notify_question_edited($unhide);
1586 redirect($this->baseurl);
1590 public function process_actions_needing_ui() {
1591 global $DB, $OUTPUT;
1592 if (optional_param('deleteselected', false, PARAM_BOOL)) {
1593 // make a list of all the questions that are selected
1594 $rawquestions = $_REQUEST; // This code is called by both POST forms and GET links, so cannot use data_submitted.
1595 $questionlist = ''; // comma separated list of ids of questions to be deleted
1596 $questionnames = ''; // string with names of questions separated by <br /> with
1597 // an asterix in front of those that are in use
1598 $inuse = false; // set to true if at least one of the questions is in use
1599 foreach ($rawquestions as $key => $value) { // Parse input for question ids
1600 if (preg_match('!^q([0-9]+)$!', $key, $matches)) {
1601 $key = $matches[1];
1602 $questionlist .= $key.',';
1603 question_require_capability_on($key, 'edit');
1604 if (questions_in_use(array($key))) {
1605 $questionnames .= '* ';
1606 $inuse = true;
1608 $questionnames .= $DB->get_field('question', 'name', array('id' => $key)) . '<br />';
1611 if (!$questionlist) { // no questions were selected
1612 redirect($this->baseurl);
1614 $questionlist = rtrim($questionlist, ',');
1616 // Add an explanation about questions in use
1617 if ($inuse) {
1618 $questionnames .= '<br />'.get_string('questionsinuse', 'question');
1620 $baseurl = new moodle_url('edit.php', $this->baseurl->params());
1621 $deleteurl = new moodle_url($baseurl, array('deleteselected'=>$questionlist, 'confirm'=>md5($questionlist), 'sesskey'=>sesskey()));
1623 echo $OUTPUT->confirm(get_string('deletequestionscheck', 'question', $questionnames), $deleteurl, $baseurl);
1625 return true;
1631 * Common setup for all pages for editing questions.
1632 * @param string $baseurl the name of the script calling this funciton. For examle 'qusetion/edit.php'.
1633 * @param string $edittab code for this edit tab
1634 * @param bool $requirecmid require cmid? default false
1635 * @param bool $requirecourseid require courseid, if cmid is not given? default true
1636 * @return array $thispageurl, $contexts, $cmid, $cm, $module, $pagevars
1638 function question_edit_setup($edittab, $baseurl, $requirecmid = false, $requirecourseid = true) {
1639 global $DB, $PAGE;
1641 $thispageurl = new moodle_url($baseurl);
1642 $thispageurl->remove_all_params(); // We are going to explicity add back everything important - this avoids unwanted params from being retained.
1644 if ($requirecmid){
1645 $cmid =required_param('cmid', PARAM_INT);
1646 } else {
1647 $cmid = optional_param('cmid', 0, PARAM_INT);
1649 if ($cmid){
1650 list($module, $cm) = get_module_from_cmid($cmid);
1651 $courseid = $cm->course;
1652 $thispageurl->params(compact('cmid'));
1653 require_login($courseid, false, $cm);
1654 $thiscontext = context_module::instance($cmid);
1655 } else {
1656 $module = null;
1657 $cm = null;
1658 if ($requirecourseid){
1659 $courseid = required_param('courseid', PARAM_INT);
1660 } else {
1661 $courseid = optional_param('courseid', 0, PARAM_INT);
1663 if ($courseid){
1664 $thispageurl->params(compact('courseid'));
1665 require_login($courseid, false);
1666 $thiscontext = context_course::instance($courseid);
1667 } else {
1668 $thiscontext = null;
1672 if ($thiscontext){
1673 $contexts = new question_edit_contexts($thiscontext);
1674 $contexts->require_one_edit_tab_cap($edittab);
1676 } else {
1677 $contexts = null;
1680 $PAGE->set_pagelayout('admin');
1682 $pagevars['qpage'] = optional_param('qpage', -1, PARAM_INT);
1684 //pass 'cat' from page to page and when 'category' comes from a drop down menu
1685 //then we also reset the qpage so we go to page 1 of
1686 //a new cat.
1687 $pagevars['cat'] = optional_param('cat', 0, PARAM_SEQUENCE); // if empty will be set up later
1688 if ($category = optional_param('category', 0, PARAM_SEQUENCE)) {
1689 if ($pagevars['cat'] != $category) { // is this a move to a new category?
1690 $pagevars['cat'] = $category;
1691 $pagevars['qpage'] = 0;
1694 if ($pagevars['cat']){
1695 $thispageurl->param('cat', $pagevars['cat']);
1697 if (strpos($baseurl, '/question/') === 0) {
1698 navigation_node::override_active_url($thispageurl);
1701 if ($pagevars['qpage'] > -1) {
1702 $thispageurl->param('qpage', $pagevars['qpage']);
1703 } else {
1704 $pagevars['qpage'] = 0;
1707 $pagevars['qperpage'] = question_get_display_preference(
1708 'qperpage', DEFAULT_QUESTIONS_PER_PAGE, PARAM_INT, $thispageurl);
1710 for ($i = 1; $i <= question_bank_view::MAX_SORTS; $i++) {
1711 $param = 'qbs' . $i;
1712 if (!$sort = optional_param($param, '', PARAM_ALPHAEXT)) {
1713 break;
1715 $thispageurl->param($param, $sort);
1718 $defaultcategory = question_make_default_categories($contexts->all());
1720 $contextlistarr = array();
1721 foreach ($contexts->having_one_edit_tab_cap($edittab) as $context){
1722 $contextlistarr[] = "'$context->id'";
1724 $contextlist = join($contextlistarr, ' ,');
1725 if (!empty($pagevars['cat'])){
1726 $catparts = explode(',', $pagevars['cat']);
1727 if (!$catparts[0] || (false !== array_search($catparts[1], $contextlistarr)) ||
1728 !$DB->count_records_select("question_categories", "id = ? AND contextid = ?", array($catparts[0], $catparts[1]))) {
1729 print_error('invalidcategory', 'question');
1731 } else {
1732 $category = $defaultcategory;
1733 $pagevars['cat'] = "$category->id,$category->contextid";
1736 // Display options.
1737 $pagevars['recurse'] = question_get_display_preference('recurse', 1, PARAM_BOOL, $thispageurl);
1738 $pagevars['showhidden'] = question_get_display_preference('showhidden', 0, PARAM_BOOL, $thispageurl);
1739 $pagevars['qbshowtext'] = question_get_display_preference('qbshowtext', 0, PARAM_BOOL, $thispageurl);
1741 // Category list page.
1742 $pagevars['cpage'] = optional_param('cpage', 1, PARAM_INT);
1743 if ($pagevars['cpage'] != 1){
1744 $thispageurl->param('cpage', $pagevars['cpage']);
1747 return array($thispageurl, $contexts, $cmid, $cm, $module, $pagevars);
1751 * Get a particular question preference that is also stored as a user preference.
1752 * If the the value is given in the GET/POST request, then that value is used,
1753 * and the user preference is updated to that value. Otherwise, the last set
1754 * value of the user preference is used, or if it has never been set the default
1755 * passed to this function.
1757 * @param string $param the param name. The URL parameter set, and the GET/POST
1758 * parameter read. The user_preference name is 'question_bank_' . $param.
1759 * @param mixed $default The default value to use, if not otherwise set.
1760 * @param int $type one of the PARAM_... constants.
1761 * @param moodle_url $thispageurl if the value has been explicitly set, we add
1762 * it to this URL.
1763 * @return mixed the parameter value to use.
1765 function question_get_display_preference($param, $default, $type, $thispageurl) {
1766 $submittedvalue = optional_param($param, null, $type);
1767 if (is_null($submittedvalue)) {
1768 return get_user_preferences('question_bank_' . $param, $default);
1771 set_user_preference('question_bank_' . $param, $submittedvalue);
1772 $thispageurl->param($param, $submittedvalue);
1773 return $submittedvalue;
1777 * Make sure user is logged in as required in this context.
1779 function require_login_in_context($contextorid = null){
1780 global $DB, $CFG;
1781 if (!is_object($contextorid)){
1782 $context = context::instance_by_id($contextorid, IGNORE_MISSING);
1783 } else {
1784 $context = $contextorid;
1786 if ($context && ($context->contextlevel == CONTEXT_COURSE)) {
1787 require_login($context->instanceid);
1788 } else if ($context && ($context->contextlevel == CONTEXT_MODULE)) {
1789 if ($cm = $DB->get_record('course_modules',array('id' =>$context->instanceid))) {
1790 if (!$course = $DB->get_record('course', array('id' => $cm->course))) {
1791 print_error('invalidcourseid');
1793 require_course_login($course, true, $cm);
1795 } else {
1796 print_error('invalidcoursemodule');
1798 } else if ($context && ($context->contextlevel == CONTEXT_SYSTEM)) {
1799 if (!empty($CFG->forcelogin)) {
1800 require_login();
1803 } else {
1804 require_login();
1809 * Print a form to let the user choose which question type to add.
1810 * When the form is submitted, it goes to the question.php script.
1811 * @param $hiddenparams hidden parameters to add to the form, in addition to
1812 * the qtype radio buttons.
1813 * @param $allowedqtypes optional list of qtypes that are allowed. If given, only
1814 * those qtypes will be shown. Example value array('description', 'multichoice').
1816 function print_choose_qtype_to_add_form($hiddenparams, array $allowedqtypes = null) {
1817 global $CFG, $PAGE, $OUTPUT;
1819 echo '<div id="chooseqtypehead" class="hd">' . "\n";
1820 echo $OUTPUT->heading(get_string('chooseqtypetoadd', 'question'), 3);
1821 echo "</div>\n";
1822 echo '<div id="chooseqtype">' . "\n";
1823 echo '<form action="' . $CFG->wwwroot . '/question/question.php" method="get"><div id="qtypeformdiv">' . "\n";
1824 foreach ($hiddenparams as $name => $value) {
1825 echo '<input type="hidden" name="' . s($name) . '" value="' . s($value) . '" />' . "\n";
1827 echo "</div>\n";
1828 echo '<div class="qtypes">' . "\n";
1829 echo '<div class="instruction">' . get_string('selectaqtypefordescription', 'question') . "</div>\n";
1830 echo '<div class="alloptions">' . "\n";
1831 echo '<div class="realqtypes">' . "\n";
1832 $fakeqtypes = array();
1833 foreach (question_bank::get_creatable_qtypes() as $qtypename => $qtype) {
1834 if ($allowedqtypes && !in_array($qtypename, $allowedqtypes)) {
1835 continue;
1837 if ($qtype->is_real_question_type()) {
1838 print_qtype_to_add_option($qtype);
1839 } else {
1840 $fakeqtypes[] = $qtype;
1843 echo "</div>\n";
1844 echo '<div class="fakeqtypes">' . "\n";
1845 foreach ($fakeqtypes as $qtype) {
1846 print_qtype_to_add_option($qtype);
1848 echo "</div>\n";
1849 echo "</div>\n";
1850 echo "</div>\n";
1851 echo '<div class="submitbuttons">' . "\n";
1852 echo '<input type="submit" value="' . get_string('next') . '" id="chooseqtype_submit" />' . "\n";
1853 echo '<input type="submit" id="chooseqtypecancel" name="addcancel" value="' . get_string('cancel') . '" />' . "\n";
1854 echo "</div></form>\n";
1855 echo "</div>\n";
1857 $PAGE->requires->js('/question/qengine.js');
1858 $module = array(
1859 'name' => 'qbank',
1860 'fullpath' => '/question/qbank.js',
1861 'requires' => array('yui2-dom', 'yui2-event', 'yui2-container'),
1862 'strings' => array(),
1863 'async' => false,
1865 $PAGE->requires->js_init_call('qtype_chooser.init', array('chooseqtype'), false, $module);
1869 * Private function used by the preceding one.
1870 * @param question_type $qtype the question type.
1872 function print_qtype_to_add_option($qtype) {
1873 echo '<div class="qtypeoption">' . "\n";
1874 echo '<label for="' . $qtype->plugin_name() . '">';
1875 echo '<input type="radio" name="qtype" id="' . $qtype->plugin_name() .
1876 '" value="' . $qtype->name() . '" />';
1877 echo '<span class="qtypename">';
1878 $fakequestion = new stdClass();
1879 $fakequestion->qtype = $qtype->name();
1880 echo print_question_icon($fakequestion);
1881 echo $qtype->menu_name() . '</span><span class="qtypesummary">' .
1882 get_string('pluginnamesummary', $qtype->plugin_name());
1883 echo "</span></label>\n";
1884 echo "</div>\n";
1888 * Print a button for creating a new question. This will open question/addquestion.php,
1889 * which in turn goes to question/question.php before getting back to $params['returnurl']
1890 * (by default the question bank screen).
1892 * @param int $categoryid The id of the category that the new question should be added to.
1893 * @param array $params Other paramters to add to the URL. You need either $params['cmid'] or
1894 * $params['courseid'], and you should probably set $params['returnurl']
1895 * @param string $caption the text to display on the button.
1896 * @param string $tooltip a tooltip to add to the button (optional).
1897 * @param bool $disabled if true, the button will be disabled.
1899 function create_new_question_button($categoryid, $params, $caption, $tooltip = '', $disabled = false) {
1900 global $CFG, $PAGE, $OUTPUT;
1901 static $choiceformprinted = false;
1902 $params['category'] = $categoryid;
1903 $url = new moodle_url('/question/addquestion.php', $params);
1904 echo $OUTPUT->single_button($url, $caption, 'get', array('disabled'=>$disabled, 'title'=>$tooltip));
1906 if (!$choiceformprinted) {
1907 echo '<div id="qtypechoicecontainer">';
1908 print_choose_qtype_to_add_form(array());
1909 echo "</div>\n";
1910 $choiceformprinted = true;