MDL-31025 navigation: When calling load_section_activities you must provide an array...
[moodle.git] / question / editlib.php
blobc433cbe513b319efb44f4c286dec44258be425cb
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
57 * @author added by Howard Miller June 2004
59 function get_questions_category( $category, $noparent=false, $recurse=true, $export=true ) {
60 global $DB;
62 // questions will be added to an array
63 $qresults = array();
65 // build sql bit for $noparent
66 $npsql = '';
67 if ($noparent) {
68 $npsql = " and parent='0' ";
71 // Get list of categories
72 if ($recurse) {
73 $categorylist = question_categorylist($category->id);
74 } else {
75 $categorylist = array($category->id);
78 // get the list of questions for the category
79 list($usql, $params) = $DB->get_in_or_equal($categorylist);
80 if ($questions = $DB->get_records_select('question', "category $usql $npsql", $params, 'qtype, name')) {
82 // iterate through questions, getting stuff we need
83 foreach($questions as $question) {
84 $question->export_process = $export;
85 question_bank::get_qtype($question->qtype)->get_question_options($question);
86 $qresults[] = $question;
90 return $qresults;
93 /**
94 * @param int $categoryid a category id.
95 * @return bool whether this is the only top-level category in a context.
97 function question_is_only_toplevel_category_in_context($categoryid) {
98 global $DB;
99 return 1 == $DB->count_records_sql("
100 SELECT count(*)
101 FROM {question_categories} c1,
102 {question_categories} c2
103 WHERE c2.id = ?
104 AND c1.contextid = c2.contextid
105 AND c1.parent = 0 AND c2.parent = 0", array($categoryid));
109 * Check whether this user is allowed to delete this category.
111 * @param int $todelete a category id.
113 function question_can_delete_cat($todelete) {
114 global $DB;
115 if (question_is_only_toplevel_category_in_context($todelete)) {
116 print_error('cannotdeletecate', 'question');
117 } else {
118 $contextid = $DB->get_field('question_categories', 'contextid', array('id' => $todelete));
119 require_capability('moodle/question:managecategory', get_context_instance_by_id($contextid));
125 * Base class for representing a column in a {@link question_bank_view}.
127 * @copyright 2009 Tim Hunt
128 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
130 abstract class question_bank_column_base {
132 * @var question_bank_view
134 protected $qbank;
137 * Constructor.
138 * @param $qbank the question_bank_view we are helping to render.
140 public function __construct(question_bank_view $qbank) {
141 $this->qbank = $qbank;
142 $this->init();
146 * A chance for subclasses to initialise themselves, for example to load lang strings,
147 * without having to override the constructor.
149 protected function init() {
152 public function is_extra_row() {
153 return false;
157 * Output the column header cell.
159 public function display_header() {
160 echo '<th class="header ' . $this->get_classes() . '" scope="col">';
161 $sortable = $this->is_sortable();
162 $name = $this->get_name();
163 $title = $this->get_title();
164 $tip = $this->get_title_tip();
165 if (is_array($sortable)) {
166 if ($title) {
167 echo '<div class="title">' . $title . '</div>';
169 $links = array();
170 foreach ($sortable as $subsort => $details) {
171 $links[] = $this->make_sort_link($name . '_' . $subsort,
172 $details['title'], '', !empty($details['reverse']));
174 echo '<div class="sorters">' . implode(' / ', $links) . '</div>';
175 } else if ($sortable) {
176 echo $this->make_sort_link($name, $title, $tip);
177 } else {
178 if ($tip) {
179 echo '<span title="' . $tip . '">';
181 echo $title;
182 if ($tip) {
183 echo '</span>';
186 echo "</th>\n";
190 * Title for this column. Not used if is_sortable returns an array.
191 * @param object $question the row from the $question table, augmented with extra information.
192 * @param string $rowclasses CSS class names that should be applied to this row of output.
194 protected abstract function get_title();
197 * @return string a fuller version of the name. Use this when get_title() returns
198 * something very short, and you want a longer version as a tool tip.
200 protected function get_title_tip() {
201 return '';
205 * Get a link that changes the sort order, and indicates the current sort state.
206 * @param $name internal name used for this type of sorting.
207 * @param $currentsort the current sort order -1, 0, 1 for descending, none, ascending.
208 * @param $title the link text.
209 * @param $defaultreverse whether the default sort order for this column is descending, rather than ascending.
210 * @return string HTML fragment.
212 protected function make_sort_link($sort, $title, $tip, $defaultreverse = false) {
213 $currentsort = $this->qbank->get_primary_sort_order($sort);
214 $newsortreverse = $defaultreverse;
215 if ($currentsort) {
216 $newsortreverse = $currentsort > 0;
218 if (!$tip) {
219 $tip = $title;
221 if ($newsortreverse) {
222 $tip = get_string('sortbyxreverse', '', $tip);
223 } else {
224 $tip = get_string('sortbyx', '', $tip);
226 $link = '<a href="' . $this->qbank->new_sort_url($sort, $newsortreverse) . '" title="' . $tip . '">';
227 $link .= $title;
228 if ($currentsort) {
229 $link .= $this->get_sort_icon($currentsort < 0);
231 $link .= '</a>';
232 return $link;
236 * Get an icon representing the corrent sort state.
237 * @param $reverse sort is descending, not ascending.
238 * @return string HTML image tag.
240 protected function get_sort_icon($reverse) {
241 global $OUTPUT;
242 if ($reverse) {
243 return ' <img src="' . $OUTPUT->pix_url('t/up') . '" alt="' . get_string('desc') . '" />';
244 } else {
245 return ' <img src="' . $OUTPUT->pix_url('t/down') . '" alt="' . get_string('asc') . '" />';
250 * Output this column.
251 * @param object $question the row from the $question table, augmented with extra information.
252 * @param string $rowclasses CSS class names that should be applied to this row of output.
254 public function display($question, $rowclasses) {
255 $this->display_start($question, $rowclasses);
256 $this->display_content($question, $rowclasses);
257 $this->display_end($question, $rowclasses);
260 protected function display_start($question, $rowclasses) {
261 echo '<td class="' . $this->get_classes() . '">';
265 * @return string the CSS classes to apply to every cell in this column.
267 protected function get_classes() {
268 $classes = $this->get_extra_classes();
269 $classes[] = $this->get_name();
270 return implode(' ', $classes);
274 * @param object $question the row from the $question table, augmented with extra information.
275 * @return string internal name for this column. Used as a CSS class name,
276 * and to store information about the current sort. Must match PARAM_ALPHA.
278 public abstract function get_name();
281 * @return array any extra class names you would like applied to every cell in this column.
283 public function get_extra_classes() {
284 return array();
288 * Output the contents of this column.
289 * @param object $question the row from the $question table, augmented with extra information.
290 * @param string $rowclasses CSS class names that should be applied to this row of output.
292 protected abstract function display_content($question, $rowclasses);
294 protected function display_end($question, $rowclasses) {
295 echo "</td>\n";
299 * Return an array 'table_alias' => 'JOIN clause' to bring in any data that
300 * this column required.
302 * The return values for all the columns will be checked. It is OK if two
303 * columns join in the same table with the same alias and identical JOIN clauses.
304 * If to columns try to use the same alias with different joins, you get an error.
305 * The only table included by default is the question table, which is aliased to 'q'.
307 * It is importnat that your join simply adds additional data (or NULLs) to the
308 * existing rows of the query. It must not cause additional rows.
310 * @return array 'table_alias' => 'JOIN clause'
312 public function get_extra_joins() {
313 return array();
317 * @return array fields required. use table alias 'q' for the question table, or one of the
318 * ones from get_extra_joins. Every field requested must specify a table prefix.
320 public function get_required_fields() {
321 return array();
325 * Can this column be sorted on? You can return either:
326 * + false for no (the default),
327 * + a field name, if sorting this column corresponds to sorting on that datbase field.
328 * + an array of subnames to sort on as follows
329 * return array(
330 * 'firstname' => array('field' => 'uc.firstname', 'title' => get_string('firstname')),
331 * 'lastname' => array('field' => 'uc.lastname', 'field' => get_string('lastname')),
332 * );
333 * As well as field, and field, you can also add 'revers' => 1 if you want the default sort
334 * order to be DESC.
335 * @return mixed as above.
337 public function is_sortable() {
338 return false;
342 * Helper method for building sort clauses.
343 * @param bool $reverse whether the normal direction should be reversed.
344 * @param string $normaldir 'ASC' or 'DESC'
345 * @return string 'ASC' or 'DESC'
347 protected function sortorder($reverse) {
348 if ($reverse) {
349 return ' DESC';
350 } else {
351 return ' ASC';
356 * @param $reverse Whether to sort in the reverse of the default sort order.
357 * @param $subsort if is_sortable returns an array of subnames, then this will be
358 * one of those. Otherwise will be empty.
359 * @return string some SQL to go in the order by clause.
361 public function sort_expression($reverse, $subsort) {
362 $sortable = $this->is_sortable();
363 if (is_array($sortable)) {
364 if (array_key_exists($subsort, $sortable)) {
365 return $sortable[$subsort]['field'] . $this->sortorder($reverse, !empty($sortable[$subsort]['reverse']));
366 } else {
367 throw new coding_exception('Unexpected $subsort type: ' . $subsort);
369 } else if ($sortable) {
370 return $sortable . $this->sortorder($reverse);
371 } else {
372 throw new coding_exception('sort_expression called on a non-sortable column.');
379 * A column with a checkbox for each question with name q{questionid}.
381 * @copyright 2009 Tim Hunt
382 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
384 class question_bank_checkbox_column extends question_bank_column_base {
385 protected $strselect;
386 protected $firstrow = true;
388 public function init() {
389 $this->strselect = get_string('select');
392 public function get_name() {
393 return 'checkbox';
396 protected function get_title() {
397 return '<input type="checkbox" disabled="disabled" id="qbheadercheckbox" />';
400 protected function get_title_tip() {
401 return get_string('selectquestionsforbulk', 'question');
404 protected function display_content($question, $rowclasses) {
405 global $PAGE;
406 echo '<input title="' . $this->strselect . '" type="checkbox" name="q' .
407 $question->id . '" id="checkq' . $question->id . '" value="1"/>';
408 if ($this->firstrow) {
409 $PAGE->requires->js_function_call('question_bank.init_checkbox_column', array(get_string('selectall'),
410 get_string('deselectall'), 'checkq' . $question->id));
411 $this->firstrow = false;
415 public function get_required_fields() {
416 return array('q.id');
422 * A column type for the name of the question type.
424 * @copyright 2009 Tim Hunt
425 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
427 class question_bank_question_type_column extends question_bank_column_base {
428 public function get_name() {
429 return 'qtype';
432 protected function get_title() {
433 return get_string('qtypeveryshort', 'question');
436 protected function get_title_tip() {
437 return get_string('questiontype', 'question');
440 protected function display_content($question, $rowclasses) {
441 echo print_question_icon($question);
444 public function get_required_fields() {
445 return array('q.qtype');
448 public function is_sortable() {
449 return 'q.qtype';
455 * A column type for the name of the question name.
457 * @copyright 2009 Tim Hunt
458 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
460 class question_bank_question_name_column extends question_bank_column_base {
461 protected $checkboxespresent = null;
463 public function get_name() {
464 return 'questionname';
467 protected function get_title() {
468 return get_string('question');
471 protected function label_for($question) {
472 if (is_null($this->checkboxespresent)) {
473 $this->checkboxespresent = $this->qbank->has_column('checkbox');
475 if ($this->checkboxespresent) {
476 return 'checkq' . $question->id;
477 } else {
478 return '';
482 protected function display_content($question, $rowclasses) {
483 $labelfor = $this->label_for($question);
484 if ($labelfor) {
485 echo '<label for="' . $labelfor . '">';
487 echo format_string($question->name);
488 if ($labelfor) {
489 echo '</label>';
493 public function get_required_fields() {
494 return array('q.id', 'q.name');
497 public function is_sortable() {
498 return 'q.name';
504 * A column type for the name of the question creator.
506 * @copyright 2009 Tim Hunt
507 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
509 class question_bank_creator_name_column extends question_bank_column_base {
510 public function get_name() {
511 return 'creatorname';
514 protected function get_title() {
515 return get_string('createdby', 'question');
518 protected function display_content($question, $rowclasses) {
519 if (!empty($question->creatorfirstname) && !empty($question->creatorlastname)) {
520 $u = new stdClass();
521 $u->firstname = $question->creatorfirstname;
522 $u->lastname = $question->creatorlastname;
523 echo fullname($u);
527 public function get_extra_joins() {
528 return array('uc' => 'LEFT JOIN {user} uc ON uc.id = q.createdby');
531 public function get_required_fields() {
532 return array('uc.firstname AS creatorfirstname', 'uc.lastname AS creatorlastname');
535 public function is_sortable() {
536 return array(
537 'firstname' => array('field' => 'uc.firstname', 'title' => get_string('firstname')),
538 'lastname' => array('field' => 'uc.lastname', 'title' => get_string('lastname')),
545 * A column type for the name of the question last modifier.
547 * @copyright 2009 Tim Hunt
548 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
550 class question_bank_modifier_name_column extends question_bank_column_base {
551 public function get_name() {
552 return 'modifiername';
555 protected function get_title() {
556 return get_string('lastmodifiedby', 'question');
559 protected function display_content($question, $rowclasses) {
560 if (!empty($question->modifierfirstname) && !empty($question->modifierlastname)) {
561 $u = new stdClass();
562 $u->firstname = $question->modifierfirstname;
563 $u->lastname = $question->modifierlastname;
564 echo fullname($u);
568 public function get_extra_joins() {
569 return array('um' => 'LEFT JOIN {user} um ON um.id = q.modifiedby');
572 public function get_required_fields() {
573 return array('um.firstname AS modifierfirstname', 'um.lastname AS modifierlastname');
576 public function is_sortable() {
577 return array(
578 'firstname' => array('field' => 'um.firstname', 'title' => get_string('firstname')),
579 'lastname' => array('field' => 'um.lastname', 'title' => get_string('lastname')),
586 * A base class for actions that are an icon that lets you manipulate the question in some way.
588 * @copyright 2009 Tim Hunt
589 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
591 abstract class question_bank_action_column_base extends question_bank_column_base {
593 protected function get_title() {
594 return '&#160;';
597 public function get_extra_classes() {
598 return array('iconcol');
601 protected function print_icon($icon, $title, $url) {
602 global $OUTPUT;
603 echo '<a title="' . $title . '" href="' . $url . '">
604 <img src="' . $OUTPUT->pix_url($icon) . '" class="iconsmall" alt="' . $title . '" /></a>';
607 public function get_required_fields() {
608 return array('q.id');
614 * Base class for question bank columns that just contain an action icon.
616 * @copyright 2009 Tim Hunt
617 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
619 class question_bank_edit_action_column extends question_bank_action_column_base {
620 protected $stredit;
621 protected $strview;
623 public function init() {
624 parent::init();
625 $this->stredit = get_string('edit');
626 $this->strview = get_string('view');
629 public function get_name() {
630 return 'editaction';
633 protected function display_content($question, $rowclasses) {
634 if (question_has_capability_on($question, 'edit') ||
635 question_has_capability_on($question, 'move')) {
636 $this->print_icon('t/edit', $this->stredit, $this->qbank->edit_question_url($question->id));
637 } else {
638 $this->print_icon('i/info', $this->strview, $this->qbank->edit_question_url($question->id));
645 * Question bank columns for the preview action icon.
647 * @copyright 2009 Tim Hunt
648 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
650 class question_bank_preview_action_column extends question_bank_action_column_base {
651 protected $strpreview;
653 public function init() {
654 parent::init();
655 $this->strpreview = get_string('preview');
658 public function get_name() {
659 return 'previewaction';
662 protected function display_content($question, $rowclasses) {
663 global $OUTPUT;
664 if (question_has_capability_on($question, 'use')) {
665 // Build the icon.
666 $image = $OUTPUT->pix_icon('t/preview', $this->strpreview);
668 $link = $this->qbank->preview_question_url($question);
669 $action = new popup_action('click', $link, 'questionpreview',
670 question_preview_popup_params());
672 echo $OUTPUT->action_link($link, $image, $action, array('title' => $this->strpreview));
676 public function get_required_fields() {
677 return array('q.id');
683 * Question bank columns for the move action icon.
685 * @copyright 2009 Tim Hunt
686 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
688 class question_bank_move_action_column extends question_bank_action_column_base {
689 protected $strmove;
691 public function init() {
692 parent::init();
693 $this->strmove = get_string('move');
696 public function get_name() {
697 return 'moveaction';
700 protected function display_content($question, $rowclasses) {
701 if (question_has_capability_on($question, 'move')) {
702 $this->print_icon('t/move', $this->strmove, $this->qbank->move_question_url($question->id));
709 * action to delete (or hide) a question, or restore a previously hidden question.
711 * @copyright 2009 Tim Hunt
712 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
714 class question_bank_delete_action_column extends question_bank_action_column_base {
715 protected $strdelete;
716 protected $strrestore;
718 public function init() {
719 parent::init();
720 $this->strdelete = get_string('delete');
721 $this->strrestore = get_string('restore');
724 public function get_name() {
725 return 'deleteaction';
728 protected function display_content($question, $rowclasses) {
729 if (question_has_capability_on($question, 'edit')) {
730 if ($question->hidden) {
731 $url = new moodle_url($this->qbank->base_url(), array('unhide' => $question->id, 'sesskey'=>sesskey()));
732 $this->print_icon('t/restore', $this->strrestore, $url);
733 } else {
734 $url = new moodle_url($this->qbank->base_url(), array('deleteselected' => $question->id, 'q' . $question->id => 1, 'sesskey'=>sesskey()));
735 $this->print_icon('t/delete', $this->strdelete, $url);
740 public function get_required_fields() {
741 return array('q.id', 'q.hidden');
746 * Base class for 'columns' that are actually displayed as a row following the main question row.
748 * @copyright 2009 Tim Hunt
749 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
751 abstract class question_bank_row_base extends question_bank_column_base {
752 public function is_extra_row() {
753 return true;
756 protected function display_start($question, $rowclasses) {
757 if ($rowclasses) {
758 echo '<tr class="' . $rowclasses . '">' . "\n";
759 } else {
760 echo "<tr>\n";
762 echo '<td colspan="' . $this->qbank->get_column_count() . '" class="' . $this->get_name() . '">';
765 protected function display_end($question, $rowclasses) {
766 echo "</td></tr>\n";
771 * A column type for the name of the question name.
773 * @copyright 2009 Tim Hunt
774 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
776 class question_bank_question_text_row extends question_bank_row_base {
777 protected $formatoptions;
779 protected function init() {
780 $this->formatoptions = new stdClass();
781 $this->formatoptions->noclean = true;
782 $this->formatoptions->para = false;
785 public function get_name() {
786 return 'questiontext';
789 protected function get_title() {
790 return get_string('questiontext', 'question');
793 protected function display_content($question, $rowclasses) {
794 $text = question_rewrite_questiontext_preview_urls($question->questiontext,
795 $question->contextid, 'question', $question->id);
796 $text = format_text($text, $question->questiontextformat,
797 $this->formatoptions);
798 if ($text == '') {
799 $text = '&#160;';
801 echo $text;
804 public function get_extra_joins() {
805 return array('qc' => 'JOIN {question_categories} qc ON qc.id = q.category');
808 public function get_required_fields() {
809 return array('q.id', 'q.questiontext', 'q.questiontextformat', 'qc.contextid');
814 * This class prints a view of the question bank, including
815 * + Some controls to allow users to to select what is displayed.
816 * + A list of questions as a table.
817 * + Further controls to do things with the questions.
819 * This class gives a basic view, and provides plenty of hooks where subclasses
820 * can override parts of the display.
822 * The list of questions presented as a table is generated by creating a list of
823 * question_bank_column objects, one for each 'column' to be displayed. These
824 * manage
825 * + outputting the contents of that column, given a $question object, but also
826 * + generating the right fragments of SQL to ensure the necessary data is present,
827 * and sorted in the right order.
828 * + outputting table headers.
830 * @copyright 2009 Tim Hunt
831 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
833 class question_bank_view {
834 const MAX_SORTS = 3;
836 protected $baseurl;
837 protected $editquestionurl;
838 protected $quizorcourseid;
839 protected $contexts;
840 protected $cm;
841 protected $course;
842 protected $knowncolumntypes;
843 protected $visiblecolumns;
844 protected $extrarows;
845 protected $requiredcolumns;
846 protected $sort;
847 protected $lastchangedid;
848 protected $countsql;
849 protected $loadsql;
850 protected $sqlparams;
853 * Constructor
854 * @param question_edit_contexts $contexts
855 * @param moodle_url $pageurl
856 * @param object $course course settings
857 * @param object $cm (optional) activity settings.
859 public function __construct($contexts, $pageurl, $course, $cm = null) {
860 global $CFG, $PAGE;
862 $this->contexts = $contexts;
863 $this->baseurl = $pageurl;
864 $this->course = $course;
865 $this->cm = $cm;
867 if (!empty($cm) && $cm->modname == 'quiz') {
868 $this->quizorcourseid = '&amp;quizid=' . $cm->instance;
869 } else {
870 $this->quizorcourseid = '&amp;courseid=' .$this->course->id;
873 // Create the url of the new question page to forward to.
874 $returnurl = str_replace($CFG->wwwroot, '', $pageurl->out(false));
875 $this->editquestionurl = new moodle_url('/question/question.php',
876 array('returnurl' => $returnurl));
877 if ($cm !== null){
878 $this->editquestionurl->param('cmid', $cm->id);
879 } else {
880 $this->editquestionurl->param('courseid', $this->course->id);
883 $this->lastchangedid = optional_param('lastchanged',0,PARAM_INT);
885 $this->init_column_types();
886 $this->init_columns($this->wanted_columns());
887 $this->init_sort();
889 $PAGE->requires->yui2_lib('container');
892 protected function wanted_columns() {
893 $columns = array('checkbox', 'qtype', 'questionname', 'editaction',
894 'previewaction', 'moveaction', 'deleteaction', 'creatorname',
895 'modifiername');
896 if (optional_param('qbshowtext', false, PARAM_BOOL)) {
897 $columns[] = 'questiontext';
899 return $columns;
902 protected function known_field_types() {
903 return array(
904 new question_bank_checkbox_column($this),
905 new question_bank_question_type_column($this),
906 new question_bank_question_name_column($this),
907 new question_bank_creator_name_column($this),
908 new question_bank_modifier_name_column($this),
909 new question_bank_edit_action_column($this),
910 new question_bank_preview_action_column($this),
911 new question_bank_move_action_column($this),
912 new question_bank_delete_action_column($this),
913 new question_bank_question_text_row($this),
917 protected function init_column_types() {
918 $this->knowncolumntypes = array();
919 foreach ($this->known_field_types() as $col) {
920 $this->knowncolumntypes[$col->get_name()] = $col;
924 protected function init_columns($wanted) {
925 $this->visiblecolumns = array();
926 $this->extrarows = array();
927 foreach ($wanted as $colname) {
928 if (!isset($this->knowncolumntypes[$colname])) {
929 throw new coding_exception('Unknown column type ' . $colname . ' requested in init columns.');
931 $column = $this->knowncolumntypes[$colname];
932 if ($column->is_extra_row()) {
933 $this->extrarows[$colname] = $column;
934 } else {
935 $this->visiblecolumns[$colname] = $column;
938 $this->requiredcolumns = array_merge($this->visiblecolumns, $this->extrarows);
942 * @param string $colname a column internal name.
943 * @return bool is this column included in the output?
945 public function has_column($colname) {
946 return isset($this->visiblecolumns[$colname]);
950 * @return int The number of columns in the table.
952 public function get_column_count() {
953 return count($this->visiblecolumns);
956 public function get_courseid() {
957 return $this->course->id;
960 protected function init_sort() {
961 $this->init_sort_from_params();
962 if (empty($this->sort)) {
963 $this->sort = $this->default_sort();
968 * Deal with a sort name of the form columnname, or colname_subsort by
969 * breaking it up, validating the bits that are presend, and returning them.
970 * If there is no subsort, then $subsort is returned as ''.
971 * @return array array($colname, $subsort).
973 protected function parse_subsort($sort) {
974 /// Do the parsing.
975 if (strpos($sort, '_') !== false) {
976 list($colname, $subsort) = explode('_', $sort, 2);
977 } else {
978 $colname = $sort;
979 $subsort = '';
981 /// Validate the column name.
982 if (!isset($this->knowncolumntypes[$colname]) || !$this->knowncolumntypes[$colname]->is_sortable()) {
983 for ($i = 1; $i <= question_bank_view::MAX_SORTS; $i++) {
984 $this->baseurl->remove_params('qbs' . $i);
986 throw new moodle_exception('unknownsortcolumn', '', $link = $this->baseurl->out(), $colname);
988 /// Validate the subsort, if present.
989 if ($subsort) {
990 $subsorts = $this->knowncolumntypes[$colname]->is_sortable();
991 if (!is_array($subsorts) || !isset($subsorts[$subsort])) {
992 throw new moodle_exception('unknownsortcolumn', '', $link = $this->baseurl->out(), $sort);
995 return array($colname, $subsort);
998 protected function init_sort_from_params() {
999 $this->sort = array();
1000 for ($i = 1; $i <= question_bank_view::MAX_SORTS; $i++) {
1001 if (!$sort = optional_param('qbs' . $i, '', PARAM_ALPHAEXT)) {
1002 break;
1004 // Work out the appropriate order.
1005 $order = 1;
1006 if ($sort[0] == '-') {
1007 $order = -1;
1008 $sort = substr($sort, 1);
1009 if (!$sort) {
1010 break;
1013 // Deal with subsorts.
1014 list($colname, $subsort) = $this->parse_subsort($sort);
1015 $this->requiredcolumns[$colname] = $this->knowncolumntypes[$colname];
1016 $this->sort[$sort] = $order;
1020 protected function sort_to_params($sorts) {
1021 $params = array();
1022 $i = 0;
1023 foreach ($sorts as $sort => $order) {
1024 $i += 1;
1025 if ($order < 0) {
1026 $sort = '-' . $sort;
1028 $params['qbs' . $i] = $sort;
1030 return $params;
1033 protected function default_sort() {
1034 return array('qtype' => 1, 'questionname' => 1);
1038 * @param $sort a column or column_subsort name.
1039 * @return int the current sort order for this column -1, 0, 1
1041 public function get_primary_sort_order($sort) {
1042 $order = reset($this->sort);
1043 $primarysort = key($this->sort);
1044 if ($sort == $primarysort) {
1045 return $order;
1046 } else {
1047 return 0;
1052 * Get a URL to redisplay the page with a new sort for the question bank.
1053 * @param string $sort the column, or column_subsort to sort on.
1054 * @param bool $newsortreverse whether to sort in reverse order.
1055 * @return string The new URL.
1057 public function new_sort_url($sort, $newsortreverse) {
1058 if ($newsortreverse) {
1059 $order = -1;
1060 } else {
1061 $order = 1;
1063 // Tricky code to add the new sort at the start, removing it from where it was before, if it was present.
1064 $newsort = array_reverse($this->sort);
1065 if (isset($newsort[$sort])) {
1066 unset($newsort[$sort]);
1068 $newsort[$sort] = $order;
1069 $newsort = array_reverse($newsort);
1070 if (count($newsort) > question_bank_view::MAX_SORTS) {
1071 $newsort = array_slice($newsort, 0, question_bank_view::MAX_SORTS, true);
1073 return $this->baseurl->out(true, $this->sort_to_params($newsort));
1076 protected function build_query_sql($category, $recurse, $showhidden) {
1077 global $DB;
1079 /// Get the required tables.
1080 $joins = array();
1081 foreach ($this->requiredcolumns as $column) {
1082 $extrajoins = $column->get_extra_joins();
1083 foreach ($extrajoins as $prefix => $join) {
1084 if (isset($joins[$prefix]) && $joins[$prefix] != $join) {
1085 throw new coding_exception('Join ' . $join . ' conflicts with previous join ' . $joins[$prefix]);
1087 $joins[$prefix] = $join;
1091 /// Get the required fields.
1092 $fields = array('q.hidden', 'q.category');
1093 foreach ($this->visiblecolumns as $column) {
1094 $fields = array_merge($fields, $column->get_required_fields());
1096 foreach ($this->extrarows as $row) {
1097 $fields = array_merge($fields, $row->get_required_fields());
1099 $fields = array_unique($fields);
1101 /// Build the order by clause.
1102 $sorts = array();
1103 foreach ($this->sort as $sort => $order) {
1104 list($colname, $subsort) = $this->parse_subsort($sort);
1105 $sorts[] = $this->requiredcolumns[$colname]->sort_expression($order < 0, $subsort);
1108 /// Build the where clause.
1109 $tests = array('q.parent = 0');
1111 if (!$showhidden) {
1112 $tests[] = 'q.hidden = 0';
1115 if ($recurse) {
1116 $categoryids = question_categorylist($category->id);
1117 } else {
1118 $categoryids = array($category->id);
1120 list($catidtest, $params) = $DB->get_in_or_equal($categoryids, SQL_PARAMS_NAMED, 'cat');
1121 $tests[] = 'q.category ' . $catidtest;
1122 $this->sqlparams = $params;
1124 /// Build the SQL.
1125 $sql = ' FROM {question} q ' . implode(' ', $joins);
1126 $sql .= ' WHERE ' . implode(' AND ', $tests);
1127 $this->countsql = 'SELECT count(1)' . $sql;
1128 $this->loadsql = 'SELECT ' . implode(', ', $fields) . $sql . ' ORDER BY ' . implode(', ', $sorts);
1129 $this->sqlparams = $params;
1132 protected function get_question_count() {
1133 global $DB;
1134 return $DB->count_records_sql($this->countsql, $this->sqlparams);
1137 protected function load_page_questions($page, $perpage) {
1138 global $DB;
1139 $questions = $DB->get_recordset_sql($this->loadsql, $this->sqlparams, $page*$perpage, $perpage);
1140 if (!$questions->valid()) {
1141 /// No questions on this page. Reset to page 0.
1142 $questions = $DB->get_recordset_sql($this->loadsql, $this->sqlparams, 0, $perpage);
1144 return $questions;
1147 public function base_url() {
1148 return $this->baseurl;
1151 public function edit_question_url($questionid) {
1152 return $this->editquestionurl->out(true, array('id' => $questionid));
1155 public function move_question_url($questionid) {
1156 return $this->editquestionurl->out(true, array('id' => $questionid, 'movecontext' => 1));
1159 public function preview_question_url($question) {
1160 return question_preview_url($question->id, null, null, null, null,
1161 $this->contexts->lowest());
1165 * Shows the question bank editing interface.
1167 * The function also processes a number of actions:
1169 * Actions affecting the question pool:
1170 * move Moves a question to a different category
1171 * deleteselected Deletes the selected questions from the category
1172 * Other actions:
1173 * category Chooses the category
1174 * displayoptions Sets display options
1176 public function display($tabname, $page, $perpage, $cat,
1177 $recurse, $showhidden, $showquestiontext) {
1178 global $PAGE, $OUTPUT;
1180 if ($this->process_actions_needing_ui()) {
1181 return;
1184 $PAGE->requires->js('/question/qbank.js');
1186 // Category selection form
1187 echo $OUTPUT->heading(get_string('questionbank', 'question'), 2);
1189 $this->display_category_form($this->contexts->having_one_edit_tab_cap($tabname),
1190 $this->baseurl, $cat);
1191 $this->display_options($recurse, $showhidden, $showquestiontext);
1193 if (!$category = $this->get_current_category($cat)) {
1194 return;
1196 $this->print_category_info($category);
1198 // continues with list of questions
1199 $this->display_question_list($this->contexts->having_one_edit_tab_cap($tabname),
1200 $this->baseurl, $cat, $this->cm,
1201 $recurse, $page, $perpage, $showhidden, $showquestiontext,
1202 $this->contexts->having_cap('moodle/question:add'));
1205 protected function print_choose_category_message($categoryandcontext) {
1206 echo "<p style=\"text-align:center;\"><b>";
1207 print_string('selectcategoryabove', 'question');
1208 echo "</b></p>";
1211 protected function get_current_category($categoryandcontext) {
1212 global $DB, $OUTPUT;
1213 list($categoryid, $contextid) = explode(',', $categoryandcontext);
1214 if (!$categoryid) {
1215 $this->print_choose_category_message($categoryandcontext);
1216 return false;
1219 if (!$category = $DB->get_record('question_categories',
1220 array('id' => $categoryid, 'contextid' => $contextid))) {
1221 echo $OUTPUT->box_start('generalbox questionbank');
1222 echo $OUTPUT->notification('Category not found!');
1223 echo $OUTPUT->box_end();
1224 return false;
1227 return $category;
1230 protected function print_category_info($category) {
1231 $formatoptions = new stdClass();
1232 $formatoptions->noclean = true;
1233 $formatoptions->overflowdiv = true;
1234 echo '<div class="boxaligncenter">';
1235 echo format_text($category->info, $category->infoformat, $formatoptions, $this->course->id);
1236 echo "</div>\n";
1240 * prints a form to choose categories
1242 protected function display_category_form($contexts, $pageurl, $current) {
1243 global $CFG, $OUTPUT;
1245 /// Get all the existing categories now
1246 echo '<div class="choosecategory">';
1247 $catmenu = question_category_options($contexts, false, 0, true);
1249 $select = new single_select($this->baseurl, 'category', $catmenu, $current, null, 'catmenu');
1250 $select->set_label(get_string('selectacategory', 'question'));
1251 echo $OUTPUT->render($select);
1252 echo "</div>\n";
1255 protected function display_options($recurse, $showhidden, $showquestiontext) {
1256 echo '<form method="get" action="edit.php" id="displayoptions">';
1257 echo "<fieldset class='invisiblefieldset'>";
1258 echo html_writer::input_hidden_params($this->baseurl, array('recurse', 'showhidden', 'qbshowtext'));
1259 $this->display_category_form_checkbox('recurse', $recurse, get_string('includesubcategories', 'question'));
1260 $this->display_category_form_checkbox('showhidden', $showhidden, get_string('showhidden', 'question'));
1261 $this->display_category_form_checkbox('qbshowtext', $showquestiontext, get_string('showquestiontext', 'question'));
1262 echo '<noscript><div class="centerpara"><input type="submit" value="'. get_string('go') .'" />';
1263 echo '</div></noscript></fieldset></form>';
1267 * Print a single option checkbox. Used by the preceeding.
1269 protected function display_category_form_checkbox($name, $value, $label) {
1270 echo '<div><input type="hidden" id="' . $name . '_off" name="' . $name . '" value="0" />';
1271 echo '<input type="checkbox" id="' . $name . '_on" name="' . $name . '" value="1"';
1272 if ($value) {
1273 echo ' checked="checked"';
1275 echo ' onchange="getElementById(\'displayoptions\').submit(); return true;" />';
1276 echo '<label for="' . $name . '_on">' . $label . '</label>';
1277 echo "</div>\n";
1280 protected function create_new_question_form($category, $canadd) {
1281 global $CFG;
1282 echo '<div class="createnewquestion">';
1283 if ($canadd) {
1284 create_new_question_button($category->id, $this->editquestionurl->params(),
1285 get_string('createnewquestion', 'question'));
1286 } else {
1287 print_string('nopermissionadd', 'question');
1289 echo '</div>';
1293 * Prints the table of questions in a category with interactions
1295 * @param object $course The course object
1296 * @param int $categoryid The id of the question category to be displayed
1297 * @param int $cm The course module record if we are in the context of a particular module, 0 otherwise
1298 * @param int $recurse This is 1 if subcategories should be included, 0 otherwise
1299 * @param int $page The number of the page to be displayed
1300 * @param int $perpage Number of questions to show per page
1301 * @param bool $showhidden True if also hidden questions should be displayed
1302 * @param bool $showquestiontext whether the text of each question should be shown in the list
1304 protected function display_question_list($contexts, $pageurl, $categoryandcontext,
1305 $cm = null, $recurse=1, $page=0, $perpage=100, $showhidden=false,
1306 $showquestiontext = false, $addcontexts = array()) {
1307 global $CFG, $DB, $OUTPUT;
1309 $category = $this->get_current_category($categoryandcontext);
1311 $cmoptions = new stdClass();
1312 $cmoptions->hasattempts = !empty($this->quizhasattempts);
1314 $strselectall = get_string('selectall');
1315 $strselectnone = get_string('deselectall');
1316 $strdelete = get_string('delete');
1318 list($categoryid, $contextid) = explode(',', $categoryandcontext);
1319 $catcontext = get_context_instance_by_id($contextid);
1321 $canadd = has_capability('moodle/question:add', $catcontext);
1322 $caneditall =has_capability('moodle/question:editall', $catcontext);
1323 $canuseall =has_capability('moodle/question:useall', $catcontext);
1324 $canmoveall =has_capability('moodle/question:moveall', $catcontext);
1326 $this->create_new_question_form($category, $canadd);
1328 $this->build_query_sql($category, $recurse, $showhidden);
1329 $totalnumber = $this->get_question_count();
1330 if ($totalnumber == 0) {
1331 return;
1334 $questions = $this->load_page_questions($page, $perpage);
1336 echo '<div class="categorypagingbarcontainer">';
1337 $pageing_url = new moodle_url('edit.php');
1338 $r = $pageing_url->params($pageurl->params());
1339 $pagingbar = new paging_bar($totalnumber, $page, $perpage, $pageing_url);
1340 $pagingbar->pagevar = 'qpage';
1341 echo $OUTPUT->render($pagingbar);
1342 echo '</div>';
1344 echo '<form method="post" action="edit.php">';
1345 echo '<fieldset class="invisiblefieldset" style="display: block;">';
1346 echo '<input type="hidden" name="sesskey" value="'.sesskey().'" />';
1347 echo html_writer::input_hidden_params($pageurl);
1349 echo '<div class="categoryquestionscontainer">';
1350 $this->start_table();
1351 $rowcount = 0;
1352 foreach ($questions as $question) {
1353 $this->print_table_row($question, $rowcount);
1354 $rowcount += 1;
1356 $this->end_table();
1357 echo "</div>\n";
1359 echo '<div class="categorypagingbarcontainer pagingbottom">';
1360 echo $OUTPUT->render($pagingbar);
1361 if ($totalnumber > DEFAULT_QUESTIONS_PER_PAGE) {
1362 if ($perpage == DEFAULT_QUESTIONS_PER_PAGE) {
1363 $url = new moodle_url('edit.php', array_merge($pageurl->params(), array('qperpage'=>1000)));
1364 $showall = '<a href="'.$url.'">'.get_string('showall', 'moodle', $totalnumber).'</a>';
1365 } else {
1366 $url = new moodle_url('edit.php', array_merge($pageurl->params(), array('qperpage'=>DEFAULT_QUESTIONS_PER_PAGE)));
1367 $showall = '<a href="'.$url.'">'.get_string('showperpage', 'moodle', DEFAULT_QUESTIONS_PER_PAGE).'</a>';
1369 echo "<div class='paging'>$showall</div>";
1371 echo '</div>';
1373 echo '<div class="modulespecificbuttonscontainer">';
1374 if ($caneditall || $canmoveall || $canuseall){
1375 echo '<strong>&nbsp;'.get_string('withselected', 'question').':</strong><br />';
1377 if (function_exists('module_specific_buttons')) {
1378 echo module_specific_buttons($this->cm->id,$cmoptions);
1381 // print delete and move selected question
1382 if ($caneditall) {
1383 echo '<input type="submit" name="deleteselected" value="' . $strdelete . "\" />\n";
1386 if ($canmoveall && count($addcontexts)) {
1387 echo '<input type="submit" name="move" value="'.get_string('moveto', 'question')."\" />\n";
1388 question_category_select_menu($addcontexts, false, 0, "$category->id,$category->contextid");
1391 if (function_exists('module_specific_controls') && $canuseall) {
1392 $modulespecific = module_specific_controls($totalnumber, $recurse, $category, $this->cm->id,$cmoptions);
1393 if(!empty($modulespecific)){
1394 echo "<hr />$modulespecific";
1398 echo "</div>\n";
1400 echo '</fieldset>';
1401 echo "</form>\n";
1404 protected function start_table() {
1405 echo '<table id="categoryquestions">' . "\n";
1406 echo "<thead>\n";
1407 $this->print_table_headers();
1408 echo "</thead>\n";
1409 echo "<tbody>\n";
1412 protected function end_table() {
1413 echo "</tbody>\n";
1414 echo "</table>\n";
1417 protected function print_table_headers() {
1418 echo "<tr>\n";
1419 foreach ($this->visiblecolumns as $column) {
1420 $column->display_header();
1422 echo "</tr>\n";
1425 protected function get_row_classes($question, $rowcount) {
1426 $classes = array();
1427 if ($question->hidden) {
1428 $classes[] = 'dimmed_text';
1430 if ($question->id == $this->lastchangedid) {
1431 $classes[] ='highlight';
1433 if (!empty($this->extrarows)) {
1434 $classes[] = 'r' . ($rowcount % 2);
1436 return $classes;
1439 protected function print_table_row($question, $rowcount) {
1440 $rowclasses = implode(' ', $this->get_row_classes($question, $rowcount));
1441 if ($rowclasses) {
1442 echo '<tr class="' . $rowclasses . '">' . "\n";
1443 } else {
1444 echo "<tr>\n";
1446 foreach ($this->visiblecolumns as $column) {
1447 $column->display($question, $rowclasses);
1449 echo "</tr>\n";
1450 foreach ($this->extrarows as $row) {
1451 $row->display($question, $rowclasses);
1455 public function process_actions() {
1456 global $CFG, $DB;
1457 /// Now, check for commands on this page and modify variables as necessary
1458 if (optional_param('move', false, PARAM_BOOL) and confirm_sesskey()) {
1459 // Move selected questions to new category
1460 $category = required_param('category', PARAM_SEQUENCE);
1461 list($tocategoryid, $contextid) = explode(',', $category);
1462 if (! $tocategory = $DB->get_record('question_categories', array('id' => $tocategoryid, 'contextid' => $contextid))) {
1463 print_error('cannotfindcate', 'question');
1465 $tocontext = get_context_instance_by_id($contextid);
1466 require_capability('moodle/question:add', $tocontext);
1467 $rawdata = (array) data_submitted();
1468 $questionids = array();
1469 foreach ($rawdata as $key => $value) { // Parse input for question ids
1470 if (preg_match('!^q([0-9]+)$!', $key, $matches)) {
1471 $key = $matches[1];
1472 $questionids[] = $key;
1475 if ($questionids) {
1476 list($usql, $params) = $DB->get_in_or_equal($questionids);
1477 $sql = "";
1478 $questions = $DB->get_records_sql("
1479 SELECT q.*, c.contextid
1480 FROM {question} q
1481 JOIN {question_categories} c ON c.id = q.category
1482 WHERE q.id $usql", $params);
1483 foreach ($questions as $question){
1484 question_require_capability_on($question, 'move');
1486 question_move_questions_to_category($questionids, $tocategory->id);
1487 redirect($this->baseurl->out(false,
1488 array('category' => "$tocategoryid,$contextid")));
1492 if (optional_param('deleteselected', false, PARAM_BOOL)) { // delete selected questions from the category
1493 if (($confirm = optional_param('confirm', '', PARAM_ALPHANUM)) and confirm_sesskey()) { // teacher has already confirmed the action
1494 $deleteselected = required_param('deleteselected', PARAM_RAW);
1495 if ($confirm == md5($deleteselected)) {
1496 if ($questionlist = explode(',', $deleteselected)) {
1497 // for each question either hide it if it is in use or delete it
1498 foreach ($questionlist as $questionid) {
1499 $questionid = (int)$questionid;
1500 question_require_capability_on($questionid, 'edit');
1501 if (questions_in_use(array($questionid))) {
1502 $DB->set_field('question', 'hidden', 1, array('id' => $questionid));
1503 } else {
1504 question_delete_question($questionid);
1508 redirect($this->baseurl);
1509 } else {
1510 print_error('invalidconfirm', 'question');
1515 // Unhide a question
1516 if(($unhide = optional_param('unhide', '', PARAM_INT)) and confirm_sesskey()) {
1517 question_require_capability_on($unhide, 'edit');
1518 $DB->set_field('question', 'hidden', 0, array('id' => $unhide));
1519 redirect($this->baseurl);
1523 public function process_actions_needing_ui() {
1524 global $DB, $OUTPUT;
1525 if (optional_param('deleteselected', false, PARAM_BOOL)) {
1526 // make a list of all the questions that are selected
1527 $rawquestions = $_REQUEST; // This code is called by both POST forms and GET links, so cannot use data_submitted.
1528 $questionlist = ''; // comma separated list of ids of questions to be deleted
1529 $questionnames = ''; // string with names of questions separated by <br /> with
1530 // an asterix in front of those that are in use
1531 $inuse = false; // set to true if at least one of the questions is in use
1532 foreach ($rawquestions as $key => $value) { // Parse input for question ids
1533 if (preg_match('!^q([0-9]+)$!', $key, $matches)) {
1534 $key = $matches[1];
1535 $questionlist .= $key.',';
1536 question_require_capability_on($key, 'edit');
1537 if (questions_in_use(array($key))) {
1538 $questionnames .= '* ';
1539 $inuse = true;
1541 $questionnames .= $DB->get_field('question', 'name', array('id' => $key)) . '<br />';
1544 if (!$questionlist) { // no questions were selected
1545 redirect($this->baseurl);
1547 $questionlist = rtrim($questionlist, ',');
1549 // Add an explanation about questions in use
1550 if ($inuse) {
1551 $questionnames .= '<br />'.get_string('questionsinuse', 'question');
1553 $baseurl = new moodle_url('edit.php', $this->baseurl->params());
1554 $deleteurl = new moodle_url($baseurl, array('deleteselected'=>$questionlist, 'confirm'=>md5($questionlist), 'sesskey'=>sesskey()));
1556 echo $OUTPUT->confirm(get_string('deletequestionscheck', 'question', $questionnames), $deleteurl, $baseurl);
1558 return true;
1564 * Common setup for all pages for editing questions.
1565 * @param string $baseurl the name of the script calling this funciton. For examle 'qusetion/edit.php'.
1566 * @param string $edittab code for this edit tab
1567 * @param bool $requirecmid require cmid? default false
1568 * @param bool $requirecourseid require courseid, if cmid is not given? default true
1569 * @return array $thispageurl, $contexts, $cmid, $cm, $module, $pagevars
1571 function question_edit_setup($edittab, $baseurl, $requirecmid = false, $requirecourseid = true) {
1572 global $DB, $PAGE;
1574 $thispageurl = new moodle_url($baseurl);
1575 $thispageurl->remove_all_params(); // We are going to explicity add back everything important - this avoids unwanted params from being retained.
1577 if ($requirecmid){
1578 $cmid =required_param('cmid', PARAM_INT);
1579 } else {
1580 $cmid = optional_param('cmid', 0, PARAM_INT);
1582 if ($cmid){
1583 list($module, $cm) = get_module_from_cmid($cmid);
1584 $courseid = $cm->course;
1585 $thispageurl->params(compact('cmid'));
1586 require_login($courseid, false, $cm);
1587 $thiscontext = get_context_instance(CONTEXT_MODULE, $cmid);
1588 } else {
1589 $module = null;
1590 $cm = null;
1591 if ($requirecourseid){
1592 $courseid = required_param('courseid', PARAM_INT);
1593 } else {
1594 $courseid = optional_param('courseid', 0, PARAM_INT);
1596 if ($courseid){
1597 $thispageurl->params(compact('courseid'));
1598 require_login($courseid, false);
1599 $thiscontext = get_context_instance(CONTEXT_COURSE, $courseid);
1600 } else {
1601 $thiscontext = null;
1605 if ($thiscontext){
1606 $contexts = new question_edit_contexts($thiscontext);
1607 $contexts->require_one_edit_tab_cap($edittab);
1609 } else {
1610 $contexts = null;
1613 $PAGE->set_pagelayout('admin');
1615 $pagevars['qpage'] = optional_param('qpage', -1, PARAM_INT);
1617 //pass 'cat' from page to page and when 'category' comes from a drop down menu
1618 //then we also reset the qpage so we go to page 1 of
1619 //a new cat.
1620 $pagevars['cat'] = optional_param('cat', 0, PARAM_SEQUENCE); // if empty will be set up later
1621 if ($category = optional_param('category', 0, PARAM_SEQUENCE)) {
1622 if ($pagevars['cat'] != $category) { // is this a move to a new category?
1623 $pagevars['cat'] = $category;
1624 $pagevars['qpage'] = 0;
1627 if ($pagevars['cat']){
1628 $thispageurl->param('cat', $pagevars['cat']);
1630 if (strpos($baseurl, '/question/') === 0) {
1631 navigation_node::override_active_url($thispageurl);
1634 if ($pagevars['qpage'] > -1) {
1635 $thispageurl->param('qpage', $pagevars['qpage']);
1636 } else {
1637 $pagevars['qpage'] = 0;
1640 $pagevars['qperpage'] = optional_param('qperpage', -1, PARAM_INT);
1641 if ($pagevars['qperpage'] > -1) {
1642 $thispageurl->param('qperpage', $pagevars['qperpage']);
1643 } else {
1644 $pagevars['qperpage'] = DEFAULT_QUESTIONS_PER_PAGE;
1647 for ($i = 1; $i <= question_bank_view::MAX_SORTS; $i++) {
1648 $param = 'qbs' . $i;
1649 if (!$sort = optional_param($param, '', PARAM_ALPHAEXT)) {
1650 break;
1652 $thispageurl->param($param, $sort);
1655 $defaultcategory = question_make_default_categories($contexts->all());
1657 $contextlistarr = array();
1658 foreach ($contexts->having_one_edit_tab_cap($edittab) as $context){
1659 $contextlistarr[] = "'$context->id'";
1661 $contextlist = join($contextlistarr, ' ,');
1662 if (!empty($pagevars['cat'])){
1663 $catparts = explode(',', $pagevars['cat']);
1664 if (!$catparts[0] || (false !== array_search($catparts[1], $contextlistarr)) ||
1665 !$DB->count_records_select("question_categories", "id = ? AND contextid = ?", array($catparts[0], $catparts[1]))) {
1666 print_error('invalidcategory', 'question');
1668 } else {
1669 $category = $defaultcategory;
1670 $pagevars['cat'] = "$category->id,$category->contextid";
1673 if(($recurse = optional_param('recurse', -1, PARAM_BOOL)) != -1) {
1674 $pagevars['recurse'] = $recurse;
1675 $thispageurl->param('recurse', $recurse);
1676 } else {
1677 $pagevars['recurse'] = 1;
1680 if(($showhidden = optional_param('showhidden', -1, PARAM_BOOL)) != -1) {
1681 $pagevars['showhidden'] = $showhidden;
1682 $thispageurl->param('showhidden', $showhidden);
1683 } else {
1684 $pagevars['showhidden'] = 0;
1687 if(($showquestiontext = optional_param('qbshowtext', -1, PARAM_BOOL)) != -1) {
1688 $pagevars['qbshowtext'] = $showquestiontext;
1689 $thispageurl->param('qbshowtext', $showquestiontext);
1690 } else {
1691 $pagevars['qbshowtext'] = 0;
1694 //category list page
1695 $pagevars['cpage'] = optional_param('cpage', 1, PARAM_INT);
1696 if ($pagevars['cpage'] != 1){
1697 $thispageurl->param('cpage', $pagevars['cpage']);
1700 return array($thispageurl, $contexts, $cmid, $cm, $module, $pagevars);
1704 * Make sure user is logged in as required in this context.
1706 function require_login_in_context($contextorid = null){
1707 global $DB, $CFG;
1708 if (!is_object($contextorid)){
1709 $context = get_context_instance_by_id($contextorid);
1710 } else {
1711 $context = $contextorid;
1713 if ($context && ($context->contextlevel == CONTEXT_COURSE)) {
1714 require_login($context->instanceid);
1715 } else if ($context && ($context->contextlevel == CONTEXT_MODULE)) {
1716 if ($cm = $DB->get_record('course_modules',array('id' =>$context->instanceid))) {
1717 if (!$course = $DB->get_record('course', array('id' => $cm->course))) {
1718 print_error('invalidcourseid');
1720 require_course_login($course, true, $cm);
1722 } else {
1723 print_error('invalidcoursemodule');
1725 } else if ($context && ($context->contextlevel == CONTEXT_SYSTEM)) {
1726 if (!empty($CFG->forcelogin)) {
1727 require_login();
1730 } else {
1731 require_login();
1736 * Print a form to let the user choose which question type to add.
1737 * When the form is submitted, it goes to the question.php script.
1738 * @param $hiddenparams hidden parameters to add to the form, in addition to
1739 * the qtype radio buttons.
1741 function print_choose_qtype_to_add_form($hiddenparams) {
1742 global $CFG, $PAGE, $OUTPUT;
1743 $PAGE->requires->js('/question/qbank.js');
1744 echo '<div id="chooseqtypehead" class="hd">' . "\n";
1745 echo $OUTPUT->heading(get_string('chooseqtypetoadd', 'question'), 3);
1746 echo "</div>\n";
1747 echo '<div id="chooseqtype">' . "\n";
1748 echo '<form action="' . $CFG->wwwroot . '/question/question.php" method="get"><div id="qtypeformdiv">' . "\n";
1749 foreach ($hiddenparams as $name => $value) {
1750 echo '<input type="hidden" name="' . s($name) . '" value="' . s($value) . '" />' . "\n";
1752 echo "</div>\n";
1753 echo '<div class="qtypes">' . "\n";
1754 echo '<div class="instruction">' . get_string('selectaqtypefordescription', 'question') . "</div>\n";
1755 echo '<div class="realqtypes">' . "\n";
1756 $fakeqtypes = array();
1757 foreach (question_bank::get_creatable_qtypes() as $qtype) {
1758 if ($qtype->is_real_question_type()) {
1759 print_qtype_to_add_option($qtype);
1760 } else {
1761 $fakeqtypes[] = $qtype;
1764 echo "</div>\n";
1765 echo '<div class="fakeqtypes">' . "\n";
1766 foreach ($fakeqtypes as $qtype) {
1767 print_qtype_to_add_option($qtype);
1769 echo "</div>\n";
1770 echo "</div>\n";
1771 echo '<div class="submitbuttons">' . "\n";
1772 echo '<input type="submit" value="' . get_string('next') . '" id="chooseqtype_submit" />' . "\n";
1773 echo '<input type="submit" id="chooseqtypecancel" name="addcancel" value="' . get_string('cancel') . '" />' . "\n";
1774 echo "</div></form>\n";
1775 echo "</div>\n";
1776 $PAGE->requires->js_init_call('qtype_chooser.init', array('chooseqtype'));
1780 * Private function used by the preceding one.
1781 * @param $qtype the question type.
1783 function print_qtype_to_add_option($qtype) {
1784 if (get_string_manager()->string_exists('pluginnamesummary', $qtype->plugin_name())) {
1785 $summary = get_string('pluginnamesummary', $qtype->plugin_name());
1786 } else {
1787 $summary = get_string($qtype->name() . 'summary', $qtype->plugin_name());
1790 echo '<div class="qtypeoption">' . "\n";
1791 echo '<label for="qtype_' . $qtype->name() . '">';
1792 echo '<input type="radio" name="qtype" id="qtype_' . $qtype->name() . '" value="' . $qtype->name() . '" />';
1793 echo '<span class="qtypename">';
1794 $fakequestion = new stdClass();
1795 $fakequestion->qtype = $qtype->name();
1796 echo print_question_icon($fakequestion);
1797 echo $qtype->menu_name() . '</span><span class="qtypesummary">' . $summary;
1798 echo "</span></label>\n";
1799 echo "</div>\n";
1803 * Print a button for creating a new question. This will open question/addquestion.php,
1804 * which in turn goes to question/question.php before getting back to $params['returnurl']
1805 * (by default the question bank screen).
1807 * @param int $categoryid The id of the category that the new question should be added to.
1808 * @param array $params Other paramters to add to the URL. You need either $params['cmid'] or
1809 * $params['courseid'], and you should probably set $params['returnurl']
1810 * @param string $caption the text to display on the button.
1811 * @param string $tooltip a tooltip to add to the button (optional).
1812 * @param bool $disabled if true, the button will be disabled.
1814 function create_new_question_button($categoryid, $params, $caption, $tooltip = '', $disabled = false) {
1815 global $CFG, $PAGE, $OUTPUT;
1816 static $choiceformprinted = false;
1817 $params['category'] = $categoryid;
1818 $url = new moodle_url('/question/addquestion.php', $params);
1819 echo $OUTPUT->single_button($url, $caption, 'get', array('disabled'=>$disabled, 'title'=>$tooltip));
1821 $PAGE->requires->yui2_lib('dragdrop');
1822 $PAGE->requires->yui2_lib('container');
1823 if (!$choiceformprinted) {
1824 echo '<div id="qtypechoicecontainer">';
1825 print_choose_qtype_to_add_form(array());
1826 echo "</div>\n";
1827 $choiceformprinted = true;