MDL-35275 - Left align INPUT boxes and TEXT boxes during Install process, when in...
[moodle.git] / question / editlib.php
blobbb563f718f332173a3b0aa5b5a6e3be381c78f37
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;
138 * Constructor.
139 * @param $qbank the question_bank_view we are helping to render.
141 public function __construct(question_bank_view $qbank) {
142 $this->qbank = $qbank;
143 $this->init();
147 * A chance for subclasses to initialise themselves, for example to load lang strings,
148 * without having to override the constructor.
150 protected function init() {
153 public function is_extra_row() {
154 return false;
158 * Output the column header cell.
160 public function display_header() {
161 echo '<th class="header ' . $this->get_classes() . '" scope="col">';
162 $sortable = $this->is_sortable();
163 $name = $this->get_name();
164 $title = $this->get_title();
165 $tip = $this->get_title_tip();
166 if (is_array($sortable)) {
167 if ($title) {
168 echo '<div class="title">' . $title . '</div>';
170 $links = array();
171 foreach ($sortable as $subsort => $details) {
172 $links[] = $this->make_sort_link($name . '_' . $subsort,
173 $details['title'], '', !empty($details['reverse']));
175 echo '<div class="sorters">' . implode(' / ', $links) . '</div>';
176 } else if ($sortable) {
177 echo $this->make_sort_link($name, $title, $tip);
178 } else {
179 if ($tip) {
180 echo '<span title="' . $tip . '">';
182 echo $title;
183 if ($tip) {
184 echo '</span>';
187 echo "</th>\n";
191 * Title for this column. Not used if is_sortable returns an array.
192 * @param object $question the row from the $question table, augmented with extra information.
193 * @param string $rowclasses CSS class names that should be applied to this row of output.
195 protected abstract function get_title();
198 * @return string a fuller version of the name. Use this when get_title() returns
199 * something very short, and you want a longer version as a tool tip.
201 protected function get_title_tip() {
202 return '';
206 * Get a link that changes the sort order, and indicates the current sort state.
207 * @param $name internal name used for this type of sorting.
208 * @param $currentsort the current sort order -1, 0, 1 for descending, none, ascending.
209 * @param $title the link text.
210 * @param $defaultreverse whether the default sort order for this column is descending, rather than ascending.
211 * @return string HTML fragment.
213 protected function make_sort_link($sort, $title, $tip, $defaultreverse = false) {
214 $currentsort = $this->qbank->get_primary_sort_order($sort);
215 $newsortreverse = $defaultreverse;
216 if ($currentsort) {
217 $newsortreverse = $currentsort > 0;
219 if (!$tip) {
220 $tip = $title;
222 if ($newsortreverse) {
223 $tip = get_string('sortbyxreverse', '', $tip);
224 } else {
225 $tip = get_string('sortbyx', '', $tip);
227 $link = '<a href="' . $this->qbank->new_sort_url($sort, $newsortreverse) . '" title="' . $tip . '">';
228 $link .= $title;
229 if ($currentsort) {
230 $link .= $this->get_sort_icon($currentsort < 0);
232 $link .= '</a>';
233 return $link;
237 * Get an icon representing the corrent sort state.
238 * @param $reverse sort is descending, not ascending.
239 * @return string HTML image tag.
241 protected function get_sort_icon($reverse) {
242 global $OUTPUT;
243 if ($reverse) {
244 return ' <img src="' . $OUTPUT->pix_url('t/up') . '" alt="' . get_string('desc') . '" />';
245 } else {
246 return ' <img src="' . $OUTPUT->pix_url('t/down') . '" alt="' . get_string('asc') . '" />';
251 * Output this column.
252 * @param object $question the row from the $question table, augmented with extra information.
253 * @param string $rowclasses CSS class names that should be applied to this row of output.
255 public function display($question, $rowclasses) {
256 $this->display_start($question, $rowclasses);
257 $this->display_content($question, $rowclasses);
258 $this->display_end($question, $rowclasses);
261 protected function display_start($question, $rowclasses) {
262 echo '<td class="' . $this->get_classes() . '">';
266 * @return string the CSS classes to apply to every cell in this column.
268 protected function get_classes() {
269 $classes = $this->get_extra_classes();
270 $classes[] = $this->get_name();
271 return implode(' ', $classes);
275 * @param object $question the row from the $question table, augmented with extra information.
276 * @return string internal name for this column. Used as a CSS class name,
277 * and to store information about the current sort. Must match PARAM_ALPHA.
279 public abstract function get_name();
282 * @return array any extra class names you would like applied to every cell in this column.
284 public function get_extra_classes() {
285 return array();
289 * Output the contents of this column.
290 * @param object $question the row from the $question table, augmented with extra information.
291 * @param string $rowclasses CSS class names that should be applied to this row of output.
293 protected abstract function display_content($question, $rowclasses);
295 protected function display_end($question, $rowclasses) {
296 echo "</td>\n";
300 * Return an array 'table_alias' => 'JOIN clause' to bring in any data that
301 * this column required.
303 * The return values for all the columns will be checked. It is OK if two
304 * columns join in the same table with the same alias and identical JOIN clauses.
305 * If to columns try to use the same alias with different joins, you get an error.
306 * The only table included by default is the question table, which is aliased to 'q'.
308 * It is importnat that your join simply adds additional data (or NULLs) to the
309 * existing rows of the query. It must not cause additional rows.
311 * @return array 'table_alias' => 'JOIN clause'
313 public function get_extra_joins() {
314 return array();
318 * @return array fields required. use table alias 'q' for the question table, or one of the
319 * ones from get_extra_joins. Every field requested must specify a table prefix.
321 public function get_required_fields() {
322 return array();
326 * Can this column be sorted on? You can return either:
327 * + false for no (the default),
328 * + a field name, if sorting this column corresponds to sorting on that datbase field.
329 * + an array of subnames to sort on as follows
330 * return array(
331 * 'firstname' => array('field' => 'uc.firstname', 'title' => get_string('firstname')),
332 * 'lastname' => array('field' => 'uc.lastname', 'field' => get_string('lastname')),
333 * );
334 * As well as field, and field, you can also add 'revers' => 1 if you want the default sort
335 * order to be DESC.
336 * @return mixed as above.
338 public function is_sortable() {
339 return false;
343 * Helper method for building sort clauses.
344 * @param bool $reverse whether the normal direction should be reversed.
345 * @param string $normaldir 'ASC' or 'DESC'
346 * @return string 'ASC' or 'DESC'
348 protected function sortorder($reverse) {
349 if ($reverse) {
350 return ' DESC';
351 } else {
352 return ' ASC';
357 * @param $reverse Whether to sort in the reverse of the default sort order.
358 * @param $subsort if is_sortable returns an array of subnames, then this will be
359 * one of those. Otherwise will be empty.
360 * @return string some SQL to go in the order by clause.
362 public function sort_expression($reverse, $subsort) {
363 $sortable = $this->is_sortable();
364 if (is_array($sortable)) {
365 if (array_key_exists($subsort, $sortable)) {
366 return $sortable[$subsort]['field'] . $this->sortorder($reverse, !empty($sortable[$subsort]['reverse']));
367 } else {
368 throw new coding_exception('Unexpected $subsort type: ' . $subsort);
370 } else if ($sortable) {
371 return $sortable . $this->sortorder($reverse);
372 } else {
373 throw new coding_exception('sort_expression called on a non-sortable column.');
380 * A column with a checkbox for each question with name q{questionid}.
382 * @copyright 2009 Tim Hunt
383 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
385 class question_bank_checkbox_column extends question_bank_column_base {
386 protected $strselect;
387 protected $firstrow = true;
389 public function init() {
390 $this->strselect = get_string('select');
393 public function get_name() {
394 return 'checkbox';
397 protected function get_title() {
398 return '<input type="checkbox" disabled="disabled" id="qbheadercheckbox" />';
401 protected function get_title_tip() {
402 return get_string('selectquestionsforbulk', 'question');
405 protected function display_content($question, $rowclasses) {
406 global $PAGE;
407 echo '<input title="' . $this->strselect . '" type="checkbox" name="q' .
408 $question->id . '" id="checkq' . $question->id . '" value="1"/>';
409 if ($this->firstrow) {
410 $PAGE->requires->js('/question/qengine.js');
411 $module = array(
412 'name' => 'qbank',
413 'fullpath' => '/question/qbank.js',
414 'requires' => array('yui2-dom', 'yui2-event', 'yui2-container'),
415 'strings' => array(),
416 'async' => false,
418 $PAGE->requires->js_init_call('question_bank.init_checkbox_column', array(get_string('selectall'),
419 get_string('deselectall'), 'checkq' . $question->id), false, $module);
420 $this->firstrow = false;
424 public function get_required_fields() {
425 return array('q.id');
431 * A column type for the name of the question type.
433 * @copyright 2009 Tim Hunt
434 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
436 class question_bank_question_type_column extends question_bank_column_base {
437 public function get_name() {
438 return 'qtype';
441 protected function get_title() {
442 return get_string('qtypeveryshort', 'question');
445 protected function get_title_tip() {
446 return get_string('questiontype', 'question');
449 protected function display_content($question, $rowclasses) {
450 echo print_question_icon($question);
453 public function get_required_fields() {
454 return array('q.qtype');
457 public function is_sortable() {
458 return 'q.qtype';
464 * A column type for the name of the question name.
466 * @copyright 2009 Tim Hunt
467 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
469 class question_bank_question_name_column extends question_bank_column_base {
470 protected $checkboxespresent = null;
472 public function get_name() {
473 return 'questionname';
476 protected function get_title() {
477 return get_string('question');
480 protected function label_for($question) {
481 if (is_null($this->checkboxespresent)) {
482 $this->checkboxespresent = $this->qbank->has_column('checkbox');
484 if ($this->checkboxespresent) {
485 return 'checkq' . $question->id;
486 } else {
487 return '';
491 protected function display_content($question, $rowclasses) {
492 $labelfor = $this->label_for($question);
493 if ($labelfor) {
494 echo '<label for="' . $labelfor . '">';
496 echo format_string($question->name);
497 if ($labelfor) {
498 echo '</label>';
502 public function get_required_fields() {
503 return array('q.id', 'q.name');
506 public function is_sortable() {
507 return 'q.name';
513 * A column type for the name of the question creator.
515 * @copyright 2009 Tim Hunt
516 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
518 class question_bank_creator_name_column extends question_bank_column_base {
519 public function get_name() {
520 return 'creatorname';
523 protected function get_title() {
524 return get_string('createdby', 'question');
527 protected function display_content($question, $rowclasses) {
528 if (!empty($question->creatorfirstname) && !empty($question->creatorlastname)) {
529 $u = new stdClass();
530 $u->firstname = $question->creatorfirstname;
531 $u->lastname = $question->creatorlastname;
532 echo fullname($u);
536 public function get_extra_joins() {
537 return array('uc' => 'LEFT JOIN {user} uc ON uc.id = q.createdby');
540 public function get_required_fields() {
541 return array('uc.firstname AS creatorfirstname', 'uc.lastname AS creatorlastname');
544 public function is_sortable() {
545 return array(
546 'firstname' => array('field' => 'uc.firstname', 'title' => get_string('firstname')),
547 'lastname' => array('field' => 'uc.lastname', 'title' => get_string('lastname')),
554 * A column type for the name of the question last modifier.
556 * @copyright 2009 Tim Hunt
557 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
559 class question_bank_modifier_name_column extends question_bank_column_base {
560 public function get_name() {
561 return 'modifiername';
564 protected function get_title() {
565 return get_string('lastmodifiedby', 'question');
568 protected function display_content($question, $rowclasses) {
569 if (!empty($question->modifierfirstname) && !empty($question->modifierlastname)) {
570 $u = new stdClass();
571 $u->firstname = $question->modifierfirstname;
572 $u->lastname = $question->modifierlastname;
573 echo fullname($u);
577 public function get_extra_joins() {
578 return array('um' => 'LEFT JOIN {user} um ON um.id = q.modifiedby');
581 public function get_required_fields() {
582 return array('um.firstname AS modifierfirstname', 'um.lastname AS modifierlastname');
585 public function is_sortable() {
586 return array(
587 'firstname' => array('field' => 'um.firstname', 'title' => get_string('firstname')),
588 'lastname' => array('field' => 'um.lastname', 'title' => get_string('lastname')),
595 * A base class for actions that are an icon that lets you manipulate the question in some way.
597 * @copyright 2009 Tim Hunt
598 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
600 abstract class question_bank_action_column_base extends question_bank_column_base {
602 protected function get_title() {
603 return '&#160;';
606 public function get_extra_classes() {
607 return array('iconcol');
610 protected function print_icon($icon, $title, $url) {
611 global $OUTPUT;
612 echo '<a title="' . $title . '" href="' . $url . '">
613 <img src="' . $OUTPUT->pix_url($icon) . '" class="iconsmall" alt="' . $title . '" /></a>';
616 public function get_required_fields() {
617 // createdby is required for permission checks.
618 return array('q.id', 'q.createdby');
624 * Base class for question bank columns that just contain an action icon.
626 * @copyright 2009 Tim Hunt
627 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
629 class question_bank_edit_action_column extends question_bank_action_column_base {
630 protected $stredit;
631 protected $strview;
633 public function init() {
634 parent::init();
635 $this->stredit = get_string('edit');
636 $this->strview = get_string('view');
639 public function get_name() {
640 return 'editaction';
643 protected function display_content($question, $rowclasses) {
644 if (question_has_capability_on($question, 'edit')) {
645 $this->print_icon('t/edit', $this->stredit, $this->qbank->edit_question_url($question->id));
646 } else if (question_has_capability_on($question, 'view')) {
647 $this->print_icon('i/info', $this->strview, $this->qbank->edit_question_url($question->id));
654 * Question bank columns for the preview action icon.
656 * @copyright 2009 Tim Hunt
657 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
659 class question_bank_preview_action_column extends question_bank_action_column_base {
660 protected $strpreview;
662 public function init() {
663 parent::init();
664 $this->strpreview = get_string('preview');
667 public function get_name() {
668 return 'previewaction';
671 protected function display_content($question, $rowclasses) {
672 global $OUTPUT;
673 if (question_has_capability_on($question, 'use')) {
674 // Build the icon.
675 $image = $OUTPUT->pix_icon('t/preview', $this->strpreview);
677 $link = $this->qbank->preview_question_url($question);
678 $action = new popup_action('click', $link, 'questionpreview',
679 question_preview_popup_params());
681 echo $OUTPUT->action_link($link, $image, $action, array('title' => $this->strpreview));
685 public function get_required_fields() {
686 return array('q.id');
692 * Question bank columns for the move action icon.
694 * @copyright 2009 Tim Hunt
695 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
697 class question_bank_move_action_column extends question_bank_action_column_base {
698 protected $strmove;
700 public function init() {
701 parent::init();
702 $this->strmove = get_string('move');
705 public function get_name() {
706 return 'moveaction';
709 protected function display_content($question, $rowclasses) {
710 if (question_has_capability_on($question, 'move')) {
711 $this->print_icon('t/move', $this->strmove, $this->qbank->move_question_url($question->id));
718 * action to delete (or hide) a question, or restore a previously hidden question.
720 * @copyright 2009 Tim Hunt
721 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
723 class question_bank_delete_action_column extends question_bank_action_column_base {
724 protected $strdelete;
725 protected $strrestore;
727 public function init() {
728 parent::init();
729 $this->strdelete = get_string('delete');
730 $this->strrestore = get_string('restore');
733 public function get_name() {
734 return 'deleteaction';
737 protected function display_content($question, $rowclasses) {
738 if (question_has_capability_on($question, 'edit')) {
739 if ($question->hidden) {
740 $url = new moodle_url($this->qbank->base_url(), array('unhide' => $question->id, 'sesskey'=>sesskey()));
741 $this->print_icon('t/restore', $this->strrestore, $url);
742 } else {
743 $url = new moodle_url($this->qbank->base_url(), array('deleteselected' => $question->id, 'q' . $question->id => 1, 'sesskey'=>sesskey()));
744 $this->print_icon('t/delete', $this->strdelete, $url);
749 public function get_required_fields() {
750 return array('q.id', 'q.hidden');
755 * Base class for 'columns' that are actually displayed as a row following the main question row.
757 * @copyright 2009 Tim Hunt
758 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
760 abstract class question_bank_row_base extends question_bank_column_base {
761 public function is_extra_row() {
762 return true;
765 protected function display_start($question, $rowclasses) {
766 if ($rowclasses) {
767 echo '<tr class="' . $rowclasses . '">' . "\n";
768 } else {
769 echo "<tr>\n";
771 echo '<td colspan="' . $this->qbank->get_column_count() . '" class="' . $this->get_name() . '">';
774 protected function display_end($question, $rowclasses) {
775 echo "</td></tr>\n";
780 * A column type for the name of the question name.
782 * @copyright 2009 Tim Hunt
783 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
785 class question_bank_question_text_row extends question_bank_row_base {
786 protected $formatoptions;
788 protected function init() {
789 $this->formatoptions = new stdClass();
790 $this->formatoptions->noclean = true;
791 $this->formatoptions->para = false;
794 public function get_name() {
795 return 'questiontext';
798 protected function get_title() {
799 return get_string('questiontext', 'question');
802 protected function display_content($question, $rowclasses) {
803 $text = question_rewrite_questiontext_preview_urls($question->questiontext,
804 $question->contextid, 'question', $question->id);
805 $text = format_text($text, $question->questiontextformat,
806 $this->formatoptions);
807 if ($text == '') {
808 $text = '&#160;';
810 echo $text;
813 public function get_extra_joins() {
814 return array('qc' => 'JOIN {question_categories} qc ON qc.id = q.category');
817 public function get_required_fields() {
818 return array('q.id', 'q.questiontext', 'q.questiontextformat', 'qc.contextid');
823 * This class prints a view of the question bank, including
824 * + Some controls to allow users to to select what is displayed.
825 * + A list of questions as a table.
826 * + Further controls to do things with the questions.
828 * This class gives a basic view, and provides plenty of hooks where subclasses
829 * can override parts of the display.
831 * The list of questions presented as a table is generated by creating a list of
832 * question_bank_column objects, one for each 'column' to be displayed. These
833 * manage
834 * + outputting the contents of that column, given a $question object, but also
835 * + generating the right fragments of SQL to ensure the necessary data is present,
836 * and sorted in the right order.
837 * + outputting table headers.
839 * @copyright 2009 Tim Hunt
840 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
842 class question_bank_view {
843 const MAX_SORTS = 3;
845 protected $baseurl;
846 protected $editquestionurl;
847 protected $quizorcourseid;
848 protected $contexts;
849 protected $cm;
850 protected $course;
851 protected $knowncolumntypes;
852 protected $visiblecolumns;
853 protected $extrarows;
854 protected $requiredcolumns;
855 protected $sort;
856 protected $lastchangedid;
857 protected $countsql;
858 protected $loadsql;
859 protected $sqlparams;
862 * Constructor
863 * @param question_edit_contexts $contexts
864 * @param moodle_url $pageurl
865 * @param object $course course settings
866 * @param object $cm (optional) activity settings.
868 public function __construct($contexts, $pageurl, $course, $cm = null) {
869 global $CFG, $PAGE;
871 $this->contexts = $contexts;
872 $this->baseurl = $pageurl;
873 $this->course = $course;
874 $this->cm = $cm;
876 if (!empty($cm) && $cm->modname == 'quiz') {
877 $this->quizorcourseid = '&amp;quizid=' . $cm->instance;
878 } else {
879 $this->quizorcourseid = '&amp;courseid=' .$this->course->id;
882 // Create the url of the new question page to forward to.
883 $returnurl = $pageurl->out_as_local_url(false);
884 $this->editquestionurl = new moodle_url('/question/question.php',
885 array('returnurl' => $returnurl));
886 if ($cm !== null){
887 $this->editquestionurl->param('cmid', $cm->id);
888 } else {
889 $this->editquestionurl->param('courseid', $this->course->id);
892 $this->lastchangedid = optional_param('lastchanged',0,PARAM_INT);
894 $this->init_column_types();
895 $this->init_columns($this->wanted_columns());
896 $this->init_sort();
899 protected function wanted_columns() {
900 $columns = array('checkbox', 'qtype', 'questionname', 'editaction',
901 'previewaction', 'moveaction', 'deleteaction', 'creatorname',
902 'modifiername');
903 if (optional_param('qbshowtext', false, PARAM_BOOL)) {
904 $columns[] = 'questiontext';
906 return $columns;
909 protected function known_field_types() {
910 return array(
911 new question_bank_checkbox_column($this),
912 new question_bank_question_type_column($this),
913 new question_bank_question_name_column($this),
914 new question_bank_creator_name_column($this),
915 new question_bank_modifier_name_column($this),
916 new question_bank_edit_action_column($this),
917 new question_bank_preview_action_column($this),
918 new question_bank_move_action_column($this),
919 new question_bank_delete_action_column($this),
920 new question_bank_question_text_row($this),
924 protected function init_column_types() {
925 $this->knowncolumntypes = array();
926 foreach ($this->known_field_types() as $col) {
927 $this->knowncolumntypes[$col->get_name()] = $col;
931 protected function init_columns($wanted) {
932 $this->visiblecolumns = array();
933 $this->extrarows = array();
934 foreach ($wanted as $colname) {
935 if (!isset($this->knowncolumntypes[$colname])) {
936 throw new coding_exception('Unknown column type ' . $colname . ' requested in init columns.');
938 $column = $this->knowncolumntypes[$colname];
939 if ($column->is_extra_row()) {
940 $this->extrarows[$colname] = $column;
941 } else {
942 $this->visiblecolumns[$colname] = $column;
945 $this->requiredcolumns = array_merge($this->visiblecolumns, $this->extrarows);
949 * @param string $colname a column internal name.
950 * @return bool is this column included in the output?
952 public function has_column($colname) {
953 return isset($this->visiblecolumns[$colname]);
957 * @return int The number of columns in the table.
959 public function get_column_count() {
960 return count($this->visiblecolumns);
963 public function get_courseid() {
964 return $this->course->id;
967 protected function init_sort() {
968 $this->init_sort_from_params();
969 if (empty($this->sort)) {
970 $this->sort = $this->default_sort();
975 * Deal with a sort name of the form columnname, or colname_subsort by
976 * breaking it up, validating the bits that are presend, and returning them.
977 * If there is no subsort, then $subsort is returned as ''.
978 * @return array array($colname, $subsort).
980 protected function parse_subsort($sort) {
981 /// Do the parsing.
982 if (strpos($sort, '_') !== false) {
983 list($colname, $subsort) = explode('_', $sort, 2);
984 } else {
985 $colname = $sort;
986 $subsort = '';
988 /// Validate the column name.
989 if (!isset($this->knowncolumntypes[$colname]) || !$this->knowncolumntypes[$colname]->is_sortable()) {
990 for ($i = 1; $i <= question_bank_view::MAX_SORTS; $i++) {
991 $this->baseurl->remove_params('qbs' . $i);
993 throw new moodle_exception('unknownsortcolumn', '', $link = $this->baseurl->out(), $colname);
995 /// Validate the subsort, if present.
996 if ($subsort) {
997 $subsorts = $this->knowncolumntypes[$colname]->is_sortable();
998 if (!is_array($subsorts) || !isset($subsorts[$subsort])) {
999 throw new moodle_exception('unknownsortcolumn', '', $link = $this->baseurl->out(), $sort);
1002 return array($colname, $subsort);
1005 protected function init_sort_from_params() {
1006 $this->sort = array();
1007 for ($i = 1; $i <= question_bank_view::MAX_SORTS; $i++) {
1008 if (!$sort = optional_param('qbs' . $i, '', PARAM_ALPHAEXT)) {
1009 break;
1011 // Work out the appropriate order.
1012 $order = 1;
1013 if ($sort[0] == '-') {
1014 $order = -1;
1015 $sort = substr($sort, 1);
1016 if (!$sort) {
1017 break;
1020 // Deal with subsorts.
1021 list($colname, $subsort) = $this->parse_subsort($sort);
1022 $this->requiredcolumns[$colname] = $this->knowncolumntypes[$colname];
1023 $this->sort[$sort] = $order;
1027 protected function sort_to_params($sorts) {
1028 $params = array();
1029 $i = 0;
1030 foreach ($sorts as $sort => $order) {
1031 $i += 1;
1032 if ($order < 0) {
1033 $sort = '-' . $sort;
1035 $params['qbs' . $i] = $sort;
1037 return $params;
1040 protected function default_sort() {
1041 $this->requiredcolumns['qtype'] = $this->knowncolumntypes['qtype'];
1042 $this->requiredcolumns['questionname'] = $this->knowncolumntypes['questionname'];
1043 return array('qtype' => 1, 'questionname' => 1);
1047 * @param $sort a column or column_subsort name.
1048 * @return int the current sort order for this column -1, 0, 1
1050 public function get_primary_sort_order($sort) {
1051 $order = reset($this->sort);
1052 $primarysort = key($this->sort);
1053 if ($sort == $primarysort) {
1054 return $order;
1055 } else {
1056 return 0;
1061 * Get a URL to redisplay the page with a new sort for the question bank.
1062 * @param string $sort the column, or column_subsort to sort on.
1063 * @param bool $newsortreverse whether to sort in reverse order.
1064 * @return string The new URL.
1066 public function new_sort_url($sort, $newsortreverse) {
1067 if ($newsortreverse) {
1068 $order = -1;
1069 } else {
1070 $order = 1;
1072 // Tricky code to add the new sort at the start, removing it from where it was before, if it was present.
1073 $newsort = array_reverse($this->sort);
1074 if (isset($newsort[$sort])) {
1075 unset($newsort[$sort]);
1077 $newsort[$sort] = $order;
1078 $newsort = array_reverse($newsort);
1079 if (count($newsort) > question_bank_view::MAX_SORTS) {
1080 $newsort = array_slice($newsort, 0, question_bank_view::MAX_SORTS, true);
1082 return $this->baseurl->out(true, $this->sort_to_params($newsort));
1085 protected function build_query_sql($category, $recurse, $showhidden) {
1086 global $DB;
1088 /// Get the required tables.
1089 $joins = array();
1090 foreach ($this->requiredcolumns as $column) {
1091 $extrajoins = $column->get_extra_joins();
1092 foreach ($extrajoins as $prefix => $join) {
1093 if (isset($joins[$prefix]) && $joins[$prefix] != $join) {
1094 throw new coding_exception('Join ' . $join . ' conflicts with previous join ' . $joins[$prefix]);
1096 $joins[$prefix] = $join;
1100 /// Get the required fields.
1101 $fields = array('q.hidden', 'q.category');
1102 foreach ($this->visiblecolumns as $column) {
1103 $fields = array_merge($fields, $column->get_required_fields());
1105 foreach ($this->extrarows as $row) {
1106 $fields = array_merge($fields, $row->get_required_fields());
1108 $fields = array_unique($fields);
1110 /// Build the order by clause.
1111 $sorts = array();
1112 foreach ($this->sort as $sort => $order) {
1113 list($colname, $subsort) = $this->parse_subsort($sort);
1114 $sorts[] = $this->requiredcolumns[$colname]->sort_expression($order < 0, $subsort);
1117 /// Build the where clause.
1118 $tests = array('q.parent = 0');
1120 if (!$showhidden) {
1121 $tests[] = 'q.hidden = 0';
1124 if ($recurse) {
1125 $categoryids = question_categorylist($category->id);
1126 } else {
1127 $categoryids = array($category->id);
1129 list($catidtest, $params) = $DB->get_in_or_equal($categoryids, SQL_PARAMS_NAMED, 'cat');
1130 $tests[] = 'q.category ' . $catidtest;
1131 $this->sqlparams = $params;
1133 /// Build the SQL.
1134 $sql = ' FROM {question} q ' . implode(' ', $joins);
1135 $sql .= ' WHERE ' . implode(' AND ', $tests);
1136 $this->countsql = 'SELECT count(1)' . $sql;
1137 $this->loadsql = 'SELECT ' . implode(', ', $fields) . $sql . ' ORDER BY ' . implode(', ', $sorts);
1138 $this->sqlparams = $params;
1141 protected function get_question_count() {
1142 global $DB;
1143 return $DB->count_records_sql($this->countsql, $this->sqlparams);
1146 protected function load_page_questions($page, $perpage) {
1147 global $DB;
1148 $questions = $DB->get_recordset_sql($this->loadsql, $this->sqlparams, $page*$perpage, $perpage);
1149 if (!$questions->valid()) {
1150 /// No questions on this page. Reset to page 0.
1151 $questions = $DB->get_recordset_sql($this->loadsql, $this->sqlparams, 0, $perpage);
1153 return $questions;
1156 public function base_url() {
1157 return $this->baseurl;
1160 public function edit_question_url($questionid) {
1161 return $this->editquestionurl->out(true, array('id' => $questionid));
1164 public function move_question_url($questionid) {
1165 return $this->editquestionurl->out(true, array('id' => $questionid, 'movecontext' => 1));
1168 public function preview_question_url($question) {
1169 return question_preview_url($question->id, null, null, null, null,
1170 $this->contexts->lowest());
1174 * Shows the question bank editing interface.
1176 * The function also processes a number of actions:
1178 * Actions affecting the question pool:
1179 * move Moves a question to a different category
1180 * deleteselected Deletes the selected questions from the category
1181 * Other actions:
1182 * category Chooses the category
1183 * displayoptions Sets display options
1185 public function display($tabname, $page, $perpage, $cat,
1186 $recurse, $showhidden, $showquestiontext) {
1187 global $PAGE, $OUTPUT;
1189 if ($this->process_actions_needing_ui()) {
1190 return;
1193 // Category selection form
1194 echo $OUTPUT->heading(get_string('questionbank', 'question'), 2);
1196 $this->display_category_form($this->contexts->having_one_edit_tab_cap($tabname),
1197 $this->baseurl, $cat);
1198 $this->display_options($recurse, $showhidden, $showquestiontext);
1200 if (!$category = $this->get_current_category($cat)) {
1201 return;
1203 $this->print_category_info($category);
1205 // continues with list of questions
1206 $this->display_question_list($this->contexts->having_one_edit_tab_cap($tabname),
1207 $this->baseurl, $cat, $this->cm,
1208 $recurse, $page, $perpage, $showhidden, $showquestiontext,
1209 $this->contexts->having_cap('moodle/question:add'));
1212 protected function print_choose_category_message($categoryandcontext) {
1213 echo "<p style=\"text-align:center;\"><b>";
1214 print_string('selectcategoryabove', 'question');
1215 echo "</b></p>";
1218 protected function get_current_category($categoryandcontext) {
1219 global $DB, $OUTPUT;
1220 list($categoryid, $contextid) = explode(',', $categoryandcontext);
1221 if (!$categoryid) {
1222 $this->print_choose_category_message($categoryandcontext);
1223 return false;
1226 if (!$category = $DB->get_record('question_categories',
1227 array('id' => $categoryid, 'contextid' => $contextid))) {
1228 echo $OUTPUT->box_start('generalbox questionbank');
1229 echo $OUTPUT->notification('Category not found!');
1230 echo $OUTPUT->box_end();
1231 return false;
1234 return $category;
1237 protected function print_category_info($category) {
1238 $formatoptions = new stdClass();
1239 $formatoptions->noclean = true;
1240 $formatoptions->overflowdiv = true;
1241 echo '<div class="boxaligncenter">';
1242 echo format_text($category->info, $category->infoformat, $formatoptions, $this->course->id);
1243 echo "</div>\n";
1247 * prints a form to choose categories
1249 protected function display_category_form($contexts, $pageurl, $current) {
1250 global $CFG, $OUTPUT;
1252 /// Get all the existing categories now
1253 echo '<div class="choosecategory">';
1254 $catmenu = question_category_options($contexts, false, 0, true);
1256 $select = new single_select($this->baseurl, 'category', $catmenu, $current, null, 'catmenu');
1257 $select->set_label(get_string('selectacategory', 'question'));
1258 echo $OUTPUT->render($select);
1259 echo "</div>\n";
1262 protected function display_options($recurse, $showhidden, $showquestiontext) {
1263 echo '<form method="get" action="edit.php" id="displayoptions">';
1264 echo "<fieldset class='invisiblefieldset'>";
1265 echo html_writer::input_hidden_params($this->baseurl, array('recurse', 'showhidden', 'qbshowtext'));
1266 $this->display_category_form_checkbox('recurse', $recurse, get_string('includesubcategories', 'question'));
1267 $this->display_category_form_checkbox('showhidden', $showhidden, get_string('showhidden', 'question'));
1268 $this->display_category_form_checkbox('qbshowtext', $showquestiontext, get_string('showquestiontext', 'question'));
1269 echo '<noscript><div class="centerpara"><input type="submit" value="'. get_string('go') .'" />';
1270 echo '</div></noscript></fieldset></form>';
1274 * Print a single option checkbox. Used by the preceeding.
1276 protected function display_category_form_checkbox($name, $value, $label) {
1277 echo '<div><input type="hidden" id="' . $name . '_off" name="' . $name . '" value="0" />';
1278 echo '<input type="checkbox" id="' . $name . '_on" name="' . $name . '" value="1"';
1279 if ($value) {
1280 echo ' checked="checked"';
1282 echo ' onchange="getElementById(\'displayoptions\').submit(); return true;" />';
1283 echo '<label for="' . $name . '_on">' . $label . '</label>';
1284 echo "</div>\n";
1287 protected function create_new_question_form($category, $canadd) {
1288 global $CFG;
1289 echo '<div class="createnewquestion">';
1290 if ($canadd) {
1291 create_new_question_button($category->id, $this->editquestionurl->params(),
1292 get_string('createnewquestion', 'question'));
1293 } else {
1294 print_string('nopermissionadd', 'question');
1296 echo '</div>';
1300 * Prints the table of questions in a category with interactions
1302 * @param object $course The course object
1303 * @param int $categoryid The id of the question category to be displayed
1304 * @param int $cm The course module record if we are in the context of a particular module, 0 otherwise
1305 * @param int $recurse This is 1 if subcategories should be included, 0 otherwise
1306 * @param int $page The number of the page to be displayed
1307 * @param int $perpage Number of questions to show per page
1308 * @param bool $showhidden True if also hidden questions should be displayed
1309 * @param bool $showquestiontext whether the text of each question should be shown in the list
1311 protected function display_question_list($contexts, $pageurl, $categoryandcontext,
1312 $cm = null, $recurse=1, $page=0, $perpage=100, $showhidden=false,
1313 $showquestiontext = false, $addcontexts = array()) {
1314 global $CFG, $DB, $OUTPUT;
1316 $category = $this->get_current_category($categoryandcontext);
1318 $cmoptions = new stdClass();
1319 $cmoptions->hasattempts = !empty($this->quizhasattempts);
1321 $strselectall = get_string('selectall');
1322 $strselectnone = get_string('deselectall');
1323 $strdelete = get_string('delete');
1325 list($categoryid, $contextid) = explode(',', $categoryandcontext);
1326 $catcontext = context::instance_by_id($contextid);
1328 $canadd = has_capability('moodle/question:add', $catcontext);
1329 $caneditall =has_capability('moodle/question:editall', $catcontext);
1330 $canuseall =has_capability('moodle/question:useall', $catcontext);
1331 $canmoveall =has_capability('moodle/question:moveall', $catcontext);
1333 $this->create_new_question_form($category, $canadd);
1335 $this->build_query_sql($category, $recurse, $showhidden);
1336 $totalnumber = $this->get_question_count();
1337 if ($totalnumber == 0) {
1338 return;
1341 $questions = $this->load_page_questions($page, $perpage);
1343 echo '<div class="categorypagingbarcontainer">';
1344 $pageing_url = new moodle_url('edit.php');
1345 $r = $pageing_url->params($pageurl->params());
1346 $pagingbar = new paging_bar($totalnumber, $page, $perpage, $pageing_url);
1347 $pagingbar->pagevar = 'qpage';
1348 echo $OUTPUT->render($pagingbar);
1349 echo '</div>';
1351 echo '<form method="post" action="edit.php">';
1352 echo '<fieldset class="invisiblefieldset" style="display: block;">';
1353 echo '<input type="hidden" name="sesskey" value="'.sesskey().'" />';
1354 echo html_writer::input_hidden_params($pageurl);
1356 echo '<div class="categoryquestionscontainer">';
1357 $this->start_table();
1358 $rowcount = 0;
1359 foreach ($questions as $question) {
1360 $this->print_table_row($question, $rowcount);
1361 $rowcount += 1;
1363 $this->end_table();
1364 echo "</div>\n";
1366 echo '<div class="categorypagingbarcontainer pagingbottom">';
1367 echo $OUTPUT->render($pagingbar);
1368 if ($totalnumber > DEFAULT_QUESTIONS_PER_PAGE) {
1369 if ($perpage == DEFAULT_QUESTIONS_PER_PAGE) {
1370 $url = new moodle_url('edit.php', array_merge($pageurl->params(), array('qperpage'=>1000)));
1371 $showall = '<a href="'.$url.'">'.get_string('showall', 'moodle', $totalnumber).'</a>';
1372 } else {
1373 $url = new moodle_url('edit.php', array_merge($pageurl->params(), array('qperpage'=>DEFAULT_QUESTIONS_PER_PAGE)));
1374 $showall = '<a href="'.$url.'">'.get_string('showperpage', 'moodle', DEFAULT_QUESTIONS_PER_PAGE).'</a>';
1376 echo "<div class='paging'>$showall</div>";
1378 echo '</div>';
1380 echo '<div class="modulespecificbuttonscontainer">';
1381 if ($caneditall || $canmoveall || $canuseall){
1382 echo '<strong>&nbsp;'.get_string('withselected', 'question').':</strong><br />';
1384 if (function_exists('module_specific_buttons')) {
1385 echo module_specific_buttons($this->cm->id,$cmoptions);
1388 // print delete and move selected question
1389 if ($caneditall) {
1390 echo '<input type="submit" name="deleteselected" value="' . $strdelete . "\" />\n";
1393 if ($canmoveall && count($addcontexts)) {
1394 echo '<input type="submit" name="move" value="'.get_string('moveto', 'question')."\" />\n";
1395 question_category_select_menu($addcontexts, false, 0, "$category->id,$category->contextid");
1398 if (function_exists('module_specific_controls') && $canuseall) {
1399 $modulespecific = module_specific_controls($totalnumber, $recurse, $category, $this->cm->id,$cmoptions);
1400 if(!empty($modulespecific)){
1401 echo "<hr />$modulespecific";
1405 echo "</div>\n";
1407 echo '</fieldset>';
1408 echo "</form>\n";
1411 protected function start_table() {
1412 echo '<table id="categoryquestions">' . "\n";
1413 echo "<thead>\n";
1414 $this->print_table_headers();
1415 echo "</thead>\n";
1416 echo "<tbody>\n";
1419 protected function end_table() {
1420 echo "</tbody>\n";
1421 echo "</table>\n";
1424 protected function print_table_headers() {
1425 echo "<tr>\n";
1426 foreach ($this->visiblecolumns as $column) {
1427 $column->display_header();
1429 echo "</tr>\n";
1432 protected function get_row_classes($question, $rowcount) {
1433 $classes = array();
1434 if ($question->hidden) {
1435 $classes[] = 'dimmed_text';
1437 if ($question->id == $this->lastchangedid) {
1438 $classes[] ='highlight';
1440 $classes[] = 'r' . ($rowcount % 2);
1441 return $classes;
1444 protected function print_table_row($question, $rowcount) {
1445 $rowclasses = implode(' ', $this->get_row_classes($question, $rowcount));
1446 if ($rowclasses) {
1447 echo '<tr class="' . $rowclasses . '">' . "\n";
1448 } else {
1449 echo "<tr>\n";
1451 foreach ($this->visiblecolumns as $column) {
1452 $column->display($question, $rowclasses);
1454 echo "</tr>\n";
1455 foreach ($this->extrarows as $row) {
1456 $row->display($question, $rowclasses);
1460 public function process_actions() {
1461 global $CFG, $DB;
1462 /// Now, check for commands on this page and modify variables as necessary
1463 if (optional_param('move', false, PARAM_BOOL) and confirm_sesskey()) {
1464 // Move selected questions to new category
1465 $category = required_param('category', PARAM_SEQUENCE);
1466 list($tocategoryid, $contextid) = explode(',', $category);
1467 if (! $tocategory = $DB->get_record('question_categories', array('id' => $tocategoryid, 'contextid' => $contextid))) {
1468 print_error('cannotfindcate', 'question');
1470 $tocontext = context::instance_by_id($contextid);
1471 require_capability('moodle/question:add', $tocontext);
1472 $rawdata = (array) data_submitted();
1473 $questionids = array();
1474 foreach ($rawdata as $key => $value) { // Parse input for question ids
1475 if (preg_match('!^q([0-9]+)$!', $key, $matches)) {
1476 $key = $matches[1];
1477 $questionids[] = $key;
1480 if ($questionids) {
1481 list($usql, $params) = $DB->get_in_or_equal($questionids);
1482 $sql = "";
1483 $questions = $DB->get_records_sql("
1484 SELECT q.*, c.contextid
1485 FROM {question} q
1486 JOIN {question_categories} c ON c.id = q.category
1487 WHERE q.id $usql", $params);
1488 foreach ($questions as $question){
1489 question_require_capability_on($question, 'move');
1491 question_move_questions_to_category($questionids, $tocategory->id);
1492 redirect($this->baseurl->out(false,
1493 array('category' => "$tocategoryid,$contextid")));
1497 if (optional_param('deleteselected', false, PARAM_BOOL)) { // delete selected questions from the category
1498 if (($confirm = optional_param('confirm', '', PARAM_ALPHANUM)) and confirm_sesskey()) { // teacher has already confirmed the action
1499 $deleteselected = required_param('deleteselected', PARAM_RAW);
1500 if ($confirm == md5($deleteselected)) {
1501 if ($questionlist = explode(',', $deleteselected)) {
1502 // for each question either hide it if it is in use or delete it
1503 foreach ($questionlist as $questionid) {
1504 $questionid = (int)$questionid;
1505 question_require_capability_on($questionid, 'edit');
1506 if (questions_in_use(array($questionid))) {
1507 $DB->set_field('question', 'hidden', 1, array('id' => $questionid));
1508 } else {
1509 question_delete_question($questionid);
1513 redirect($this->baseurl);
1514 } else {
1515 print_error('invalidconfirm', 'question');
1520 // Unhide a question
1521 if(($unhide = optional_param('unhide', '', PARAM_INT)) and confirm_sesskey()) {
1522 question_require_capability_on($unhide, 'edit');
1523 $DB->set_field('question', 'hidden', 0, array('id' => $unhide));
1524 redirect($this->baseurl);
1528 public function process_actions_needing_ui() {
1529 global $DB, $OUTPUT;
1530 if (optional_param('deleteselected', false, PARAM_BOOL)) {
1531 // make a list of all the questions that are selected
1532 $rawquestions = $_REQUEST; // This code is called by both POST forms and GET links, so cannot use data_submitted.
1533 $questionlist = ''; // comma separated list of ids of questions to be deleted
1534 $questionnames = ''; // string with names of questions separated by <br /> with
1535 // an asterix in front of those that are in use
1536 $inuse = false; // set to true if at least one of the questions is in use
1537 foreach ($rawquestions as $key => $value) { // Parse input for question ids
1538 if (preg_match('!^q([0-9]+)$!', $key, $matches)) {
1539 $key = $matches[1];
1540 $questionlist .= $key.',';
1541 question_require_capability_on($key, 'edit');
1542 if (questions_in_use(array($key))) {
1543 $questionnames .= '* ';
1544 $inuse = true;
1546 $questionnames .= $DB->get_field('question', 'name', array('id' => $key)) . '<br />';
1549 if (!$questionlist) { // no questions were selected
1550 redirect($this->baseurl);
1552 $questionlist = rtrim($questionlist, ',');
1554 // Add an explanation about questions in use
1555 if ($inuse) {
1556 $questionnames .= '<br />'.get_string('questionsinuse', 'question');
1558 $baseurl = new moodle_url('edit.php', $this->baseurl->params());
1559 $deleteurl = new moodle_url($baseurl, array('deleteselected'=>$questionlist, 'confirm'=>md5($questionlist), 'sesskey'=>sesskey()));
1561 echo $OUTPUT->confirm(get_string('deletequestionscheck', 'question', $questionnames), $deleteurl, $baseurl);
1563 return true;
1569 * Common setup for all pages for editing questions.
1570 * @param string $baseurl the name of the script calling this funciton. For examle 'qusetion/edit.php'.
1571 * @param string $edittab code for this edit tab
1572 * @param bool $requirecmid require cmid? default false
1573 * @param bool $requirecourseid require courseid, if cmid is not given? default true
1574 * @return array $thispageurl, $contexts, $cmid, $cm, $module, $pagevars
1576 function question_edit_setup($edittab, $baseurl, $requirecmid = false, $requirecourseid = true) {
1577 global $DB, $PAGE;
1579 $thispageurl = new moodle_url($baseurl);
1580 $thispageurl->remove_all_params(); // We are going to explicity add back everything important - this avoids unwanted params from being retained.
1582 if ($requirecmid){
1583 $cmid =required_param('cmid', PARAM_INT);
1584 } else {
1585 $cmid = optional_param('cmid', 0, PARAM_INT);
1587 if ($cmid){
1588 list($module, $cm) = get_module_from_cmid($cmid);
1589 $courseid = $cm->course;
1590 $thispageurl->params(compact('cmid'));
1591 require_login($courseid, false, $cm);
1592 $thiscontext = context_module::instance($cmid);
1593 } else {
1594 $module = null;
1595 $cm = null;
1596 if ($requirecourseid){
1597 $courseid = required_param('courseid', PARAM_INT);
1598 } else {
1599 $courseid = optional_param('courseid', 0, PARAM_INT);
1601 if ($courseid){
1602 $thispageurl->params(compact('courseid'));
1603 require_login($courseid, false);
1604 $thiscontext = context_course::instance($courseid);
1605 } else {
1606 $thiscontext = null;
1610 if ($thiscontext){
1611 $contexts = new question_edit_contexts($thiscontext);
1612 $contexts->require_one_edit_tab_cap($edittab);
1614 } else {
1615 $contexts = null;
1618 $PAGE->set_pagelayout('admin');
1620 $pagevars['qpage'] = optional_param('qpage', -1, PARAM_INT);
1622 //pass 'cat' from page to page and when 'category' comes from a drop down menu
1623 //then we also reset the qpage so we go to page 1 of
1624 //a new cat.
1625 $pagevars['cat'] = optional_param('cat', 0, PARAM_SEQUENCE); // if empty will be set up later
1626 if ($category = optional_param('category', 0, PARAM_SEQUENCE)) {
1627 if ($pagevars['cat'] != $category) { // is this a move to a new category?
1628 $pagevars['cat'] = $category;
1629 $pagevars['qpage'] = 0;
1632 if ($pagevars['cat']){
1633 $thispageurl->param('cat', $pagevars['cat']);
1635 if (strpos($baseurl, '/question/') === 0) {
1636 navigation_node::override_active_url($thispageurl);
1639 if ($pagevars['qpage'] > -1) {
1640 $thispageurl->param('qpage', $pagevars['qpage']);
1641 } else {
1642 $pagevars['qpage'] = 0;
1645 $pagevars['qperpage'] = question_get_display_preference(
1646 'qperpage', DEFAULT_QUESTIONS_PER_PAGE, PARAM_INT, $thispageurl);
1648 for ($i = 1; $i <= question_bank_view::MAX_SORTS; $i++) {
1649 $param = 'qbs' . $i;
1650 if (!$sort = optional_param($param, '', PARAM_ALPHAEXT)) {
1651 break;
1653 $thispageurl->param($param, $sort);
1656 $defaultcategory = question_make_default_categories($contexts->all());
1658 $contextlistarr = array();
1659 foreach ($contexts->having_one_edit_tab_cap($edittab) as $context){
1660 $contextlistarr[] = "'$context->id'";
1662 $contextlist = join($contextlistarr, ' ,');
1663 if (!empty($pagevars['cat'])){
1664 $catparts = explode(',', $pagevars['cat']);
1665 if (!$catparts[0] || (false !== array_search($catparts[1], $contextlistarr)) ||
1666 !$DB->count_records_select("question_categories", "id = ? AND contextid = ?", array($catparts[0], $catparts[1]))) {
1667 print_error('invalidcategory', 'question');
1669 } else {
1670 $category = $defaultcategory;
1671 $pagevars['cat'] = "$category->id,$category->contextid";
1674 // Display options.
1675 $pagevars['recurse'] = question_get_display_preference('recurse', 1, PARAM_BOOL, $thispageurl);
1676 $pagevars['showhidden'] = question_get_display_preference('showhidden', 0, PARAM_BOOL, $thispageurl);
1677 $pagevars['qbshowtext'] = question_get_display_preference('qbshowtext', 0, PARAM_BOOL, $thispageurl);
1679 // Category list page.
1680 $pagevars['cpage'] = optional_param('cpage', 1, PARAM_INT);
1681 if ($pagevars['cpage'] != 1){
1682 $thispageurl->param('cpage', $pagevars['cpage']);
1685 return array($thispageurl, $contexts, $cmid, $cm, $module, $pagevars);
1689 * Get a particular question preference that is also stored as a user preference.
1690 * If the the value is given in the GET/POST request, then that value is used,
1691 * and the user preference is updated to that value. Otherwise, the last set
1692 * value of the user preference is used, or if it has never been set the default
1693 * passed to this function.
1695 * @param string $param the param name. The URL parameter set, and the GET/POST
1696 * parameter read. The user_preference name is 'question_bank_' . $param.
1697 * @param mixed $default The default value to use, if not otherwise set.
1698 * @param int $type one of the PARAM_... constants.
1699 * @param moodle_url $thispageurl if the value has been explicitly set, we add
1700 * it to this URL.
1701 * @return mixed the parameter value to use.
1703 function question_get_display_preference($param, $default, $type, $thispageurl) {
1704 $submittedvalue = optional_param($param, null, $type);
1705 if (is_null($submittedvalue)) {
1706 return get_user_preferences('question_bank_' . $param, $default);
1709 set_user_preference('question_bank_' . $param, $submittedvalue);
1710 $thispageurl->param($param, $submittedvalue);
1711 return $submittedvalue;
1715 * Make sure user is logged in as required in this context.
1717 function require_login_in_context($contextorid = null){
1718 global $DB, $CFG;
1719 if (!is_object($contextorid)){
1720 $context = context::instance_by_id($contextorid, IGNORE_MISSING);
1721 } else {
1722 $context = $contextorid;
1724 if ($context && ($context->contextlevel == CONTEXT_COURSE)) {
1725 require_login($context->instanceid);
1726 } else if ($context && ($context->contextlevel == CONTEXT_MODULE)) {
1727 if ($cm = $DB->get_record('course_modules',array('id' =>$context->instanceid))) {
1728 if (!$course = $DB->get_record('course', array('id' => $cm->course))) {
1729 print_error('invalidcourseid');
1731 require_course_login($course, true, $cm);
1733 } else {
1734 print_error('invalidcoursemodule');
1736 } else if ($context && ($context->contextlevel == CONTEXT_SYSTEM)) {
1737 if (!empty($CFG->forcelogin)) {
1738 require_login();
1741 } else {
1742 require_login();
1747 * Print a form to let the user choose which question type to add.
1748 * When the form is submitted, it goes to the question.php script.
1749 * @param $hiddenparams hidden parameters to add to the form, in addition to
1750 * the qtype radio buttons.
1751 * @param $allowedqtypes optional list of qtypes that are allowed. If given, only
1752 * those qtypes will be shown. Example value array('description', 'multichoice').
1754 function print_choose_qtype_to_add_form($hiddenparams, array $allowedqtypes = null) {
1755 global $CFG, $PAGE, $OUTPUT;
1757 echo '<div id="chooseqtypehead" class="hd">' . "\n";
1758 echo $OUTPUT->heading(get_string('chooseqtypetoadd', 'question'), 3);
1759 echo "</div>\n";
1760 echo '<div id="chooseqtype">' . "\n";
1761 echo '<form action="' . $CFG->wwwroot . '/question/question.php" method="get"><div id="qtypeformdiv">' . "\n";
1762 foreach ($hiddenparams as $name => $value) {
1763 echo '<input type="hidden" name="' . s($name) . '" value="' . s($value) . '" />' . "\n";
1765 echo "</div>\n";
1766 echo '<div class="qtypes">' . "\n";
1767 echo '<div class="instruction">' . get_string('selectaqtypefordescription', 'question') . "</div>\n";
1768 echo '<div class="realqtypes">' . "\n";
1769 $fakeqtypes = array();
1770 foreach (question_bank::get_creatable_qtypes() as $qtypename => $qtype) {
1771 if ($allowedqtypes && !in_array($qtypename, $allowedqtypes)) {
1772 continue;
1774 if ($qtype->is_real_question_type()) {
1775 print_qtype_to_add_option($qtype);
1776 } else {
1777 $fakeqtypes[] = $qtype;
1780 echo "</div>\n";
1781 echo '<div class="fakeqtypes">' . "\n";
1782 foreach ($fakeqtypes as $qtype) {
1783 print_qtype_to_add_option($qtype);
1785 echo "</div>\n";
1786 echo "</div>\n";
1787 echo '<div class="submitbuttons">' . "\n";
1788 echo '<input type="submit" value="' . get_string('next') . '" id="chooseqtype_submit" />' . "\n";
1789 echo '<input type="submit" id="chooseqtypecancel" name="addcancel" value="' . get_string('cancel') . '" />' . "\n";
1790 echo "</div></form>\n";
1791 echo "</div>\n";
1793 $PAGE->requires->js('/question/qengine.js');
1794 $module = array(
1795 'name' => 'qbank',
1796 'fullpath' => '/question/qbank.js',
1797 'requires' => array('yui2-dom', 'yui2-event', 'yui2-container'),
1798 'strings' => array(),
1799 'async' => false,
1801 $PAGE->requires->js_init_call('qtype_chooser.init', array('chooseqtype'), false, $module);
1805 * Private function used by the preceding one.
1806 * @param question_type $qtype the question type.
1808 function print_qtype_to_add_option($qtype) {
1809 echo '<div class="qtypeoption">' . "\n";
1810 echo '<label for="' . $qtype->plugin_name() . '">';
1811 echo '<input type="radio" name="qtype" id="' . $qtype->plugin_name() .
1812 '" value="' . $qtype->name() . '" />';
1813 echo '<span class="qtypename">';
1814 $fakequestion = new stdClass();
1815 $fakequestion->qtype = $qtype->name();
1816 echo print_question_icon($fakequestion);
1817 echo $qtype->menu_name() . '</span><span class="qtypesummary">' .
1818 get_string('pluginnamesummary', $qtype->plugin_name());
1819 echo "</span></label>\n";
1820 echo "</div>\n";
1824 * Print a button for creating a new question. This will open question/addquestion.php,
1825 * which in turn goes to question/question.php before getting back to $params['returnurl']
1826 * (by default the question bank screen).
1828 * @param int $categoryid The id of the category that the new question should be added to.
1829 * @param array $params Other paramters to add to the URL. You need either $params['cmid'] or
1830 * $params['courseid'], and you should probably set $params['returnurl']
1831 * @param string $caption the text to display on the button.
1832 * @param string $tooltip a tooltip to add to the button (optional).
1833 * @param bool $disabled if true, the button will be disabled.
1835 function create_new_question_button($categoryid, $params, $caption, $tooltip = '', $disabled = false) {
1836 global $CFG, $PAGE, $OUTPUT;
1837 static $choiceformprinted = false;
1838 $params['category'] = $categoryid;
1839 $url = new moodle_url('/question/addquestion.php', $params);
1840 echo $OUTPUT->single_button($url, $caption, 'get', array('disabled'=>$disabled, 'title'=>$tooltip));
1842 if (!$choiceformprinted) {
1843 echo '<div id="qtypechoicecontainer">';
1844 print_choose_qtype_to_add_form(array());
1845 echo "</div>\n";
1846 $choiceformprinted = true;