2 // This file is part of Moodle - http://moodle.org/
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.
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/>.
18 * Functions used to show question editing interface
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) {
35 if (!$cmrec = $DB->get_record_sql("SELECT cm.*, md.name as modname
36 FROM {course_modules} cm,
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);
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 ) {
61 // Build sql bit for $noparent
64 $npsql = " and parent='0' ";
67 // Get list of categories
69 $categorylist = question_categorylist($category->id);
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
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.
87 $qtype->get_question_options($question);
88 $qresults[] = $question;
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) {
100 return 1 == $DB->count_records_sql("
102 FROM {question_categories} c1,
103 {question_categories} c2
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) {
116 if (question_is_only_toplevel_category_in_context($todelete)) {
117 print_error('cannotdeletecate', 'question');
119 $contextid = $DB->get_field('question_categories', 'contextid', array('id' => $todelete));
120 require_capability('moodle/question:managecategory', get_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
139 * @param $qbank the question_bank_view we are helping to render.
141 public function __construct(question_bank_view $qbank) {
142 $this->qbank = $qbank;
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() {
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)) {
168 echo '<div class="title">' . $title . '</div>';
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);
180 echo '<span title="' . $tip . '">';
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() {
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;
217 $newsortreverse = $currentsort > 0;
222 if ($newsortreverse) {
223 $tip = get_string('sortbyxreverse', '', $tip);
225 $tip = get_string('sortbyx', '', $tip);
227 $link = '<a href="' . $this->qbank->new_sort_url($sort, $newsortreverse) . '" title="' . $tip . '">';
230 $link .= $this->get_sort_icon($currentsort < 0);
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) {
244 return ' <img src="' . $OUTPUT->pix_url('t/up') . '" alt="' . get_string('desc') . '" />';
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() {
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) {
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() {
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() {
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
331 * 'firstname' => array('field' => 'uc.firstname', 'title' => get_string('firstname')),
332 * 'lastname' => array('field' => 'uc.lastname', 'field' => get_string('lastname')),
334 * As well as field, and field, you can also add 'revers' => 1 if you want the default sort
336 * @return mixed as above.
338 public function is_sortable() {
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) {
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']));
368 throw new coding_exception('Unexpected $subsort type: ' . $subsort);
370 } else if ($sortable) {
371 return $sortable . $this->sortorder($reverse);
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() {
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) {
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_function_call('question_bank.init_checkbox_column', array(get_string('selectall'),
411 get_string('deselectall'), 'checkq' . $question->id));
412 $this->firstrow = false;
416 public function get_required_fields() {
417 return array('q.id');
423 * A column type for the name of the question type.
425 * @copyright 2009 Tim Hunt
426 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
428 class question_bank_question_type_column extends question_bank_column_base {
429 public function get_name() {
433 protected function get_title() {
434 return get_string('qtypeveryshort', 'question');
437 protected function get_title_tip() {
438 return get_string('questiontype', 'question');
441 protected function display_content($question, $rowclasses) {
442 echo print_question_icon($question);
445 public function get_required_fields() {
446 return array('q.qtype');
449 public function is_sortable() {
456 * A column type for the name of the question name.
458 * @copyright 2009 Tim Hunt
459 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
461 class question_bank_question_name_column extends question_bank_column_base {
462 protected $checkboxespresent = null;
464 public function get_name() {
465 return 'questionname';
468 protected function get_title() {
469 return get_string('question');
472 protected function label_for($question) {
473 if (is_null($this->checkboxespresent)) {
474 $this->checkboxespresent = $this->qbank->has_column('checkbox');
476 if ($this->checkboxespresent) {
477 return 'checkq' . $question->id;
483 protected function display_content($question, $rowclasses) {
484 $labelfor = $this->label_for($question);
486 echo '<label for="' . $labelfor . '">';
488 echo format_string($question->name);
494 public function get_required_fields() {
495 return array('q.id', 'q.name');
498 public function is_sortable() {
505 * A column type for the name of the question creator.
507 * @copyright 2009 Tim Hunt
508 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
510 class question_bank_creator_name_column extends question_bank_column_base {
511 public function get_name() {
512 return 'creatorname';
515 protected function get_title() {
516 return get_string('createdby', 'question');
519 protected function display_content($question, $rowclasses) {
520 if (!empty($question->creatorfirstname) && !empty($question->creatorlastname)) {
522 $u->firstname = $question->creatorfirstname;
523 $u->lastname = $question->creatorlastname;
528 public function get_extra_joins() {
529 return array('uc' => 'LEFT JOIN {user} uc ON uc.id = q.createdby');
532 public function get_required_fields() {
533 return array('uc.firstname AS creatorfirstname', 'uc.lastname AS creatorlastname');
536 public function is_sortable() {
538 'firstname' => array('field' => 'uc.firstname', 'title' => get_string('firstname')),
539 'lastname' => array('field' => 'uc.lastname', 'title' => get_string('lastname')),
546 * A column type for the name of the question last modifier.
548 * @copyright 2009 Tim Hunt
549 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
551 class question_bank_modifier_name_column extends question_bank_column_base {
552 public function get_name() {
553 return 'modifiername';
556 protected function get_title() {
557 return get_string('lastmodifiedby', 'question');
560 protected function display_content($question, $rowclasses) {
561 if (!empty($question->modifierfirstname) && !empty($question->modifierlastname)) {
563 $u->firstname = $question->modifierfirstname;
564 $u->lastname = $question->modifierlastname;
569 public function get_extra_joins() {
570 return array('um' => 'LEFT JOIN {user} um ON um.id = q.modifiedby');
573 public function get_required_fields() {
574 return array('um.firstname AS modifierfirstname', 'um.lastname AS modifierlastname');
577 public function is_sortable() {
579 'firstname' => array('field' => 'um.firstname', 'title' => get_string('firstname')),
580 'lastname' => array('field' => 'um.lastname', 'title' => get_string('lastname')),
587 * A base class for actions that are an icon that lets you manipulate the question in some way.
589 * @copyright 2009 Tim Hunt
590 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
592 abstract class question_bank_action_column_base extends question_bank_column_base {
594 protected function get_title() {
598 public function get_extra_classes() {
599 return array('iconcol');
602 protected function print_icon($icon, $title, $url) {
604 echo '<a title="' . $title . '" href="' . $url . '">
605 <img src="' . $OUTPUT->pix_url($icon) . '" class="iconsmall" alt="' . $title . '" /></a>';
608 public function get_required_fields() {
609 // createdby is required for permission checks.
610 return array('q.id, q.createdby');
616 * Base class for question bank columns that just contain an action icon.
618 * @copyright 2009 Tim Hunt
619 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
621 class question_bank_edit_action_column extends question_bank_action_column_base {
625 public function init() {
627 $this->stredit = get_string('edit');
628 $this->strview = get_string('view');
631 public function get_name() {
635 protected function display_content($question, $rowclasses) {
636 if (question_has_capability_on($question, 'edit')) {
637 $this->print_icon('t/edit', $this->stredit, $this->qbank->edit_question_url($question->id));
638 } else if (question_has_capability_on($question, 'view')) {
639 $this->print_icon('i/info', $this->strview, $this->qbank->edit_question_url($question->id));
646 * Question bank columns for the preview action icon.
648 * @copyright 2009 Tim Hunt
649 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
651 class question_bank_preview_action_column extends question_bank_action_column_base {
652 protected $strpreview;
654 public function init() {
656 $this->strpreview = get_string('preview');
659 public function get_name() {
660 return 'previewaction';
663 protected function display_content($question, $rowclasses) {
665 if (question_has_capability_on($question, 'use')) {
667 $image = $OUTPUT->pix_icon('t/preview', $this->strpreview);
669 $link = $this->qbank->preview_question_url($question);
670 $action = new popup_action('click', $link, 'questionpreview',
671 question_preview_popup_params());
673 echo $OUTPUT->action_link($link, $image, $action, array('title' => $this->strpreview));
677 public function get_required_fields() {
678 return array('q.id');
684 * Question bank columns for the move action icon.
686 * @copyright 2009 Tim Hunt
687 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
689 class question_bank_move_action_column extends question_bank_action_column_base {
692 public function init() {
694 $this->strmove = get_string('move');
697 public function get_name() {
701 protected function display_content($question, $rowclasses) {
702 if (question_has_capability_on($question, 'move')) {
703 $this->print_icon('t/move', $this->strmove, $this->qbank->move_question_url($question->id));
710 * action to delete (or hide) a question, or restore a previously hidden question.
712 * @copyright 2009 Tim Hunt
713 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
715 class question_bank_delete_action_column extends question_bank_action_column_base {
716 protected $strdelete;
717 protected $strrestore;
719 public function init() {
721 $this->strdelete = get_string('delete');
722 $this->strrestore = get_string('restore');
725 public function get_name() {
726 return 'deleteaction';
729 protected function display_content($question, $rowclasses) {
730 if (question_has_capability_on($question, 'edit')) {
731 if ($question->hidden) {
732 $url = new moodle_url($this->qbank->base_url(), array('unhide' => $question->id, 'sesskey'=>sesskey()));
733 $this->print_icon('t/restore', $this->strrestore, $url);
735 $url = new moodle_url($this->qbank->base_url(), array('deleteselected' => $question->id, 'q' . $question->id => 1, 'sesskey'=>sesskey()));
736 $this->print_icon('t/delete', $this->strdelete, $url);
741 public function get_required_fields() {
742 return array('q.id', 'q.hidden');
747 * Base class for 'columns' that are actually displayed as a row following the main question row.
749 * @copyright 2009 Tim Hunt
750 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
752 abstract class question_bank_row_base extends question_bank_column_base {
753 public function is_extra_row() {
757 protected function display_start($question, $rowclasses) {
759 echo '<tr class="' . $rowclasses . '">' . "\n";
763 echo '<td colspan="' . $this->qbank->get_column_count() . '" class="' . $this->get_name() . '">';
766 protected function display_end($question, $rowclasses) {
772 * A column type for the name of the question name.
774 * @copyright 2009 Tim Hunt
775 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
777 class question_bank_question_text_row extends question_bank_row_base {
778 protected $formatoptions;
780 protected function init() {
781 $this->formatoptions = new stdClass();
782 $this->formatoptions->noclean = true;
783 $this->formatoptions->para = false;
786 public function get_name() {
787 return 'questiontext';
790 protected function get_title() {
791 return get_string('questiontext', 'question');
794 protected function display_content($question, $rowclasses) {
795 $text = question_rewrite_questiontext_preview_urls($question->questiontext,
796 $question->contextid, 'question', $question->id);
797 $text = format_text($text, $question->questiontextformat,
798 $this->formatoptions);
805 public function get_extra_joins() {
806 return array('qc' => 'JOIN {question_categories} qc ON qc.id = q.category');
809 public function get_required_fields() {
810 return array('q.id', 'q.questiontext', 'q.questiontextformat', 'qc.contextid');
815 * This class prints a view of the question bank, including
816 * + Some controls to allow users to to select what is displayed.
817 * + A list of questions as a table.
818 * + Further controls to do things with the questions.
820 * This class gives a basic view, and provides plenty of hooks where subclasses
821 * can override parts of the display.
823 * The list of questions presented as a table is generated by creating a list of
824 * question_bank_column objects, one for each 'column' to be displayed. These
826 * + outputting the contents of that column, given a $question object, but also
827 * + generating the right fragments of SQL to ensure the necessary data is present,
828 * and sorted in the right order.
829 * + outputting table headers.
831 * @copyright 2009 Tim Hunt
832 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
834 class question_bank_view {
838 protected $editquestionurl;
839 protected $quizorcourseid;
843 protected $knowncolumntypes;
844 protected $visiblecolumns;
845 protected $extrarows;
846 protected $requiredcolumns;
848 protected $lastchangedid;
851 protected $sqlparams;
855 * @param question_edit_contexts $contexts
856 * @param moodle_url $pageurl
857 * @param object $course course settings
858 * @param object $cm (optional) activity settings.
860 public function __construct($contexts, $pageurl, $course, $cm = null) {
863 $this->contexts = $contexts;
864 $this->baseurl = $pageurl;
865 $this->course = $course;
868 if (!empty($cm) && $cm->modname == 'quiz') {
869 $this->quizorcourseid = '&quizid=' . $cm->instance;
871 $this->quizorcourseid = '&courseid=' .$this->course->id;
874 // Create the url of the new question page to forward to.
875 $returnurl = $pageurl->out_as_local_url(false);
876 $this->editquestionurl = new moodle_url('/question/question.php',
877 array('returnurl' => $returnurl));
879 $this->editquestionurl->param('cmid', $cm->id);
881 $this->editquestionurl->param('courseid', $this->course->id);
884 $this->lastchangedid = optional_param('lastchanged',0,PARAM_INT);
886 $this->init_column_types();
887 $this->init_columns($this->wanted_columns());
890 $PAGE->requires->yui2_lib('container');
893 protected function wanted_columns() {
894 $columns = array('checkbox', 'qtype', 'questionname', 'editaction',
895 'previewaction', 'moveaction', 'deleteaction', 'creatorname',
897 if (optional_param('qbshowtext', false, PARAM_BOOL)) {
898 $columns[] = 'questiontext';
903 protected function known_field_types() {
905 new question_bank_checkbox_column($this),
906 new question_bank_question_type_column($this),
907 new question_bank_question_name_column($this),
908 new question_bank_creator_name_column($this),
909 new question_bank_modifier_name_column($this),
910 new question_bank_edit_action_column($this),
911 new question_bank_preview_action_column($this),
912 new question_bank_move_action_column($this),
913 new question_bank_delete_action_column($this),
914 new question_bank_question_text_row($this),
918 protected function init_column_types() {
919 $this->knowncolumntypes = array();
920 foreach ($this->known_field_types() as $col) {
921 $this->knowncolumntypes[$col->get_name()] = $col;
925 protected function init_columns($wanted) {
926 $this->visiblecolumns = array();
927 $this->extrarows = array();
928 foreach ($wanted as $colname) {
929 if (!isset($this->knowncolumntypes[$colname])) {
930 throw new coding_exception('Unknown column type ' . $colname . ' requested in init columns.');
932 $column = $this->knowncolumntypes[$colname];
933 if ($column->is_extra_row()) {
934 $this->extrarows[$colname] = $column;
936 $this->visiblecolumns[$colname] = $column;
939 $this->requiredcolumns = array_merge($this->visiblecolumns, $this->extrarows);
943 * @param string $colname a column internal name.
944 * @return bool is this column included in the output?
946 public function has_column($colname) {
947 return isset($this->visiblecolumns[$colname]);
951 * @return int The number of columns in the table.
953 public function get_column_count() {
954 return count($this->visiblecolumns);
957 public function get_courseid() {
958 return $this->course->id;
961 protected function init_sort() {
962 $this->init_sort_from_params();
963 if (empty($this->sort)) {
964 $this->sort = $this->default_sort();
969 * Deal with a sort name of the form columnname, or colname_subsort by
970 * breaking it up, validating the bits that are presend, and returning them.
971 * If there is no subsort, then $subsort is returned as ''.
972 * @return array array($colname, $subsort).
974 protected function parse_subsort($sort) {
976 if (strpos($sort, '_') !== false) {
977 list($colname, $subsort) = explode('_', $sort, 2);
982 /// Validate the column name.
983 if (!isset($this->knowncolumntypes[$colname]) || !$this->knowncolumntypes[$colname]->is_sortable()) {
984 for ($i = 1; $i <= question_bank_view::MAX_SORTS; $i++) {
985 $this->baseurl->remove_params('qbs' . $i);
987 throw new moodle_exception('unknownsortcolumn', '', $link = $this->baseurl->out(), $colname);
989 /// Validate the subsort, if present.
991 $subsorts = $this->knowncolumntypes[$colname]->is_sortable();
992 if (!is_array($subsorts) || !isset($subsorts[$subsort])) {
993 throw new moodle_exception('unknownsortcolumn', '', $link = $this->baseurl->out(), $sort);
996 return array($colname, $subsort);
999 protected function init_sort_from_params() {
1000 $this->sort = array();
1001 for ($i = 1; $i <= question_bank_view::MAX_SORTS; $i++) {
1002 if (!$sort = optional_param('qbs' . $i, '', PARAM_ALPHAEXT)) {
1005 // Work out the appropriate order.
1007 if ($sort[0] == '-') {
1009 $sort = substr($sort, 1);
1014 // Deal with subsorts.
1015 list($colname, $subsort) = $this->parse_subsort($sort);
1016 $this->requiredcolumns[$colname] = $this->knowncolumntypes[$colname];
1017 $this->sort[$sort] = $order;
1021 protected function sort_to_params($sorts) {
1024 foreach ($sorts as $sort => $order) {
1027 $sort = '-' . $sort;
1029 $params['qbs' . $i] = $sort;
1034 protected function default_sort() {
1035 return array('qtype' => 1, 'questionname' => 1);
1039 * @param $sort a column or column_subsort name.
1040 * @return int the current sort order for this column -1, 0, 1
1042 public function get_primary_sort_order($sort) {
1043 $order = reset($this->sort);
1044 $primarysort = key($this->sort);
1045 if ($sort == $primarysort) {
1053 * Get a URL to redisplay the page with a new sort for the question bank.
1054 * @param string $sort the column, or column_subsort to sort on.
1055 * @param bool $newsortreverse whether to sort in reverse order.
1056 * @return string The new URL.
1058 public function new_sort_url($sort, $newsortreverse) {
1059 if ($newsortreverse) {
1064 // Tricky code to add the new sort at the start, removing it from where it was before, if it was present.
1065 $newsort = array_reverse($this->sort);
1066 if (isset($newsort[$sort])) {
1067 unset($newsort[$sort]);
1069 $newsort[$sort] = $order;
1070 $newsort = array_reverse($newsort);
1071 if (count($newsort) > question_bank_view::MAX_SORTS) {
1072 $newsort = array_slice($newsort, 0, question_bank_view::MAX_SORTS, true);
1074 return $this->baseurl->out(true, $this->sort_to_params($newsort));
1077 protected function build_query_sql($category, $recurse, $showhidden) {
1080 /// Get the required tables.
1082 foreach ($this->requiredcolumns as $column) {
1083 $extrajoins = $column->get_extra_joins();
1084 foreach ($extrajoins as $prefix => $join) {
1085 if (isset($joins[$prefix]) && $joins[$prefix] != $join) {
1086 throw new coding_exception('Join ' . $join . ' conflicts with previous join ' . $joins[$prefix]);
1088 $joins[$prefix] = $join;
1092 /// Get the required fields.
1093 $fields = array('q.hidden', 'q.category');
1094 foreach ($this->visiblecolumns as $column) {
1095 $fields = array_merge($fields, $column->get_required_fields());
1097 foreach ($this->extrarows as $row) {
1098 $fields = array_merge($fields, $row->get_required_fields());
1100 $fields = array_unique($fields);
1102 /// Build the order by clause.
1104 foreach ($this->sort as $sort => $order) {
1105 list($colname, $subsort) = $this->parse_subsort($sort);
1106 $sorts[] = $this->requiredcolumns[$colname]->sort_expression($order < 0, $subsort);
1109 /// Build the where clause.
1110 $tests = array('q.parent = 0');
1113 $tests[] = 'q.hidden = 0';
1117 $categoryids = question_categorylist($category->id);
1119 $categoryids = array($category->id);
1121 list($catidtest, $params) = $DB->get_in_or_equal($categoryids, SQL_PARAMS_NAMED, 'cat');
1122 $tests[] = 'q.category ' . $catidtest;
1123 $this->sqlparams = $params;
1126 $sql = ' FROM {question} q ' . implode(' ', $joins);
1127 $sql .= ' WHERE ' . implode(' AND ', $tests);
1128 $this->countsql = 'SELECT count(1)' . $sql;
1129 $this->loadsql = 'SELECT ' . implode(', ', $fields) . $sql . ' ORDER BY ' . implode(', ', $sorts);
1130 $this->sqlparams = $params;
1133 protected function get_question_count() {
1135 return $DB->count_records_sql($this->countsql, $this->sqlparams);
1138 protected function load_page_questions($page, $perpage) {
1140 $questions = $DB->get_recordset_sql($this->loadsql, $this->sqlparams, $page*$perpage, $perpage);
1141 if (!$questions->valid()) {
1142 /// No questions on this page. Reset to page 0.
1143 $questions = $DB->get_recordset_sql($this->loadsql, $this->sqlparams, 0, $perpage);
1148 public function base_url() {
1149 return $this->baseurl;
1152 public function edit_question_url($questionid) {
1153 return $this->editquestionurl->out(true, array('id' => $questionid));
1156 public function move_question_url($questionid) {
1157 return $this->editquestionurl->out(true, array('id' => $questionid, 'movecontext' => 1));
1160 public function preview_question_url($question) {
1161 return question_preview_url($question->id, null, null, null, null,
1162 $this->contexts->lowest());
1166 * Shows the question bank editing interface.
1168 * The function also processes a number of actions:
1170 * Actions affecting the question pool:
1171 * move Moves a question to a different category
1172 * deleteselected Deletes the selected questions from the category
1174 * category Chooses the category
1175 * displayoptions Sets display options
1177 public function display($tabname, $page, $perpage, $cat,
1178 $recurse, $showhidden, $showquestiontext) {
1179 global $PAGE, $OUTPUT;
1181 if ($this->process_actions_needing_ui()) {
1185 $PAGE->requires->js('/question/qbank.js');
1187 // Category selection form
1188 echo $OUTPUT->heading(get_string('questionbank', 'question'), 2);
1190 $this->display_category_form($this->contexts->having_one_edit_tab_cap($tabname),
1191 $this->baseurl, $cat);
1192 $this->display_options($recurse, $showhidden, $showquestiontext);
1194 if (!$category = $this->get_current_category($cat)) {
1197 $this->print_category_info($category);
1199 // continues with list of questions
1200 $this->display_question_list($this->contexts->having_one_edit_tab_cap($tabname),
1201 $this->baseurl, $cat, $this->cm,
1202 $recurse, $page, $perpage, $showhidden, $showquestiontext,
1203 $this->contexts->having_cap('moodle/question:add'));
1206 protected function print_choose_category_message($categoryandcontext) {
1207 echo "<p style=\"text-align:center;\"><b>";
1208 print_string('selectcategoryabove', 'question');
1212 protected function get_current_category($categoryandcontext) {
1213 global $DB, $OUTPUT;
1214 list($categoryid, $contextid) = explode(',', $categoryandcontext);
1216 $this->print_choose_category_message($categoryandcontext);
1220 if (!$category = $DB->get_record('question_categories',
1221 array('id' => $categoryid, 'contextid' => $contextid))) {
1222 echo $OUTPUT->box_start('generalbox questionbank');
1223 echo $OUTPUT->notification('Category not found!');
1224 echo $OUTPUT->box_end();
1231 protected function print_category_info($category) {
1232 $formatoptions = new stdClass();
1233 $formatoptions->noclean = true;
1234 $formatoptions->overflowdiv = true;
1235 echo '<div class="boxaligncenter">';
1236 echo format_text($category->info, $category->infoformat, $formatoptions, $this->course->id);
1241 * prints a form to choose categories
1243 protected function display_category_form($contexts, $pageurl, $current) {
1244 global $CFG, $OUTPUT;
1246 /// Get all the existing categories now
1247 echo '<div class="choosecategory">';
1248 $catmenu = question_category_options($contexts, false, 0, true);
1250 $select = new single_select($this->baseurl, 'category', $catmenu, $current, null, 'catmenu');
1251 $select->set_label(get_string('selectacategory', 'question'));
1252 echo $OUTPUT->render($select);
1256 protected function display_options($recurse, $showhidden, $showquestiontext) {
1257 echo '<form method="get" action="edit.php" id="displayoptions">';
1258 echo "<fieldset class='invisiblefieldset'>";
1259 echo html_writer::input_hidden_params($this->baseurl, array('recurse', 'showhidden', 'qbshowtext'));
1260 $this->display_category_form_checkbox('recurse', $recurse, get_string('includesubcategories', 'question'));
1261 $this->display_category_form_checkbox('showhidden', $showhidden, get_string('showhidden', 'question'));
1262 $this->display_category_form_checkbox('qbshowtext', $showquestiontext, get_string('showquestiontext', 'question'));
1263 echo '<noscript><div class="centerpara"><input type="submit" value="'. get_string('go') .'" />';
1264 echo '</div></noscript></fieldset></form>';
1268 * Print a single option checkbox. Used by the preceeding.
1270 protected function display_category_form_checkbox($name, $value, $label) {
1271 echo '<div><input type="hidden" id="' . $name . '_off" name="' . $name . '" value="0" />';
1272 echo '<input type="checkbox" id="' . $name . '_on" name="' . $name . '" value="1"';
1274 echo ' checked="checked"';
1276 echo ' onchange="getElementById(\'displayoptions\').submit(); return true;" />';
1277 echo '<label for="' . $name . '_on">' . $label . '</label>';
1281 protected function create_new_question_form($category, $canadd) {
1283 echo '<div class="createnewquestion">';
1285 create_new_question_button($category->id, $this->editquestionurl->params(),
1286 get_string('createnewquestion', 'question'));
1288 print_string('nopermissionadd', 'question');
1294 * Prints the table of questions in a category with interactions
1296 * @param object $course The course object
1297 * @param int $categoryid The id of the question category to be displayed
1298 * @param int $cm The course module record if we are in the context of a particular module, 0 otherwise
1299 * @param int $recurse This is 1 if subcategories should be included, 0 otherwise
1300 * @param int $page The number of the page to be displayed
1301 * @param int $perpage Number of questions to show per page
1302 * @param bool $showhidden True if also hidden questions should be displayed
1303 * @param bool $showquestiontext whether the text of each question should be shown in the list
1305 protected function display_question_list($contexts, $pageurl, $categoryandcontext,
1306 $cm = null, $recurse=1, $page=0, $perpage=100, $showhidden=false,
1307 $showquestiontext = false, $addcontexts = array()) {
1308 global $CFG, $DB, $OUTPUT;
1310 $category = $this->get_current_category($categoryandcontext);
1312 $cmoptions = new stdClass();
1313 $cmoptions->hasattempts = !empty($this->quizhasattempts);
1315 $strselectall = get_string('selectall');
1316 $strselectnone = get_string('deselectall');
1317 $strdelete = get_string('delete');
1319 list($categoryid, $contextid) = explode(',', $categoryandcontext);
1320 $catcontext = get_context_instance_by_id($contextid);
1322 $canadd = has_capability('moodle/question:add', $catcontext);
1323 $caneditall =has_capability('moodle/question:editall', $catcontext);
1324 $canuseall =has_capability('moodle/question:useall', $catcontext);
1325 $canmoveall =has_capability('moodle/question:moveall', $catcontext);
1327 $this->create_new_question_form($category, $canadd);
1329 $this->build_query_sql($category, $recurse, $showhidden);
1330 $totalnumber = $this->get_question_count();
1331 if ($totalnumber == 0) {
1335 $questions = $this->load_page_questions($page, $perpage);
1337 echo '<div class="categorypagingbarcontainer">';
1338 $pageing_url = new moodle_url('edit.php');
1339 $r = $pageing_url->params($pageurl->params());
1340 $pagingbar = new paging_bar($totalnumber, $page, $perpage, $pageing_url);
1341 $pagingbar->pagevar = 'qpage';
1342 echo $OUTPUT->render($pagingbar);
1345 echo '<form method="post" action="edit.php">';
1346 echo '<fieldset class="invisiblefieldset" style="display: block;">';
1347 echo '<input type="hidden" name="sesskey" value="'.sesskey().'" />';
1348 echo html_writer::input_hidden_params($pageurl);
1350 echo '<div class="categoryquestionscontainer">';
1351 $this->start_table();
1353 foreach ($questions as $question) {
1354 $this->print_table_row($question, $rowcount);
1360 echo '<div class="categorypagingbarcontainer pagingbottom">';
1361 echo $OUTPUT->render($pagingbar);
1362 if ($totalnumber > DEFAULT_QUESTIONS_PER_PAGE) {
1363 if ($perpage == DEFAULT_QUESTIONS_PER_PAGE) {
1364 $url = new moodle_url('edit.php', array_merge($pageurl->params(), array('qperpage'=>1000)));
1365 $showall = '<a href="'.$url.'">'.get_string('showall', 'moodle', $totalnumber).'</a>';
1367 $url = new moodle_url('edit.php', array_merge($pageurl->params(), array('qperpage'=>DEFAULT_QUESTIONS_PER_PAGE)));
1368 $showall = '<a href="'.$url.'">'.get_string('showperpage', 'moodle', DEFAULT_QUESTIONS_PER_PAGE).'</a>';
1370 echo "<div class='paging'>$showall</div>";
1374 echo '<div class="modulespecificbuttonscontainer">';
1375 if ($caneditall || $canmoveall || $canuseall){
1376 echo '<strong> '.get_string('withselected', 'question').':</strong><br />';
1378 if (function_exists('module_specific_buttons')) {
1379 echo module_specific_buttons($this->cm->id,$cmoptions);
1382 // print delete and move selected question
1384 echo '<input type="submit" name="deleteselected" value="' . $strdelete . "\" />\n";
1387 if ($canmoveall && count($addcontexts)) {
1388 echo '<input type="submit" name="move" value="'.get_string('moveto', 'question')."\" />\n";
1389 question_category_select_menu($addcontexts, false, 0, "$category->id,$category->contextid");
1392 if (function_exists('module_specific_controls') && $canuseall) {
1393 $modulespecific = module_specific_controls($totalnumber, $recurse, $category, $this->cm->id,$cmoptions);
1394 if(!empty($modulespecific)){
1395 echo "<hr />$modulespecific";
1405 protected function start_table() {
1406 echo '<table id="categoryquestions">' . "\n";
1408 $this->print_table_headers();
1413 protected function end_table() {
1418 protected function print_table_headers() {
1420 foreach ($this->visiblecolumns as $column) {
1421 $column->display_header();
1426 protected function get_row_classes($question, $rowcount) {
1428 if ($question->hidden) {
1429 $classes[] = 'dimmed_text';
1431 if ($question->id == $this->lastchangedid) {
1432 $classes[] ='highlight';
1434 $classes[] = 'r' . ($rowcount % 2);
1438 protected function print_table_row($question, $rowcount) {
1439 $rowclasses = implode(' ', $this->get_row_classes($question, $rowcount));
1441 echo '<tr class="' . $rowclasses . '">' . "\n";
1445 foreach ($this->visiblecolumns as $column) {
1446 $column->display($question, $rowclasses);
1449 foreach ($this->extrarows as $row) {
1450 $row->display($question, $rowclasses);
1454 public function process_actions() {
1456 /// Now, check for commands on this page and modify variables as necessary
1457 if (optional_param('move', false, PARAM_BOOL) and confirm_sesskey()) {
1458 // Move selected questions to new category
1459 $category = required_param('category', PARAM_SEQUENCE);
1460 list($tocategoryid, $contextid) = explode(',', $category);
1461 if (! $tocategory = $DB->get_record('question_categories', array('id' => $tocategoryid, 'contextid' => $contextid))) {
1462 print_error('cannotfindcate', 'question');
1464 $tocontext = get_context_instance_by_id($contextid);
1465 require_capability('moodle/question:add', $tocontext);
1466 $rawdata = (array) data_submitted();
1467 $questionids = array();
1468 foreach ($rawdata as $key => $value) { // Parse input for question ids
1469 if (preg_match('!^q([0-9]+)$!', $key, $matches)) {
1471 $questionids[] = $key;
1475 list($usql, $params) = $DB->get_in_or_equal($questionids);
1477 $questions = $DB->get_records_sql("
1478 SELECT q.*, c.contextid
1480 JOIN {question_categories} c ON c.id = q.category
1481 WHERE q.id $usql", $params);
1482 foreach ($questions as $question){
1483 question_require_capability_on($question, 'move');
1485 question_move_questions_to_category($questionids, $tocategory->id);
1486 redirect($this->baseurl->out(false,
1487 array('category' => "$tocategoryid,$contextid")));
1491 if (optional_param('deleteselected', false, PARAM_BOOL)) { // delete selected questions from the category
1492 if (($confirm = optional_param('confirm', '', PARAM_ALPHANUM)) and confirm_sesskey()) { // teacher has already confirmed the action
1493 $deleteselected = required_param('deleteselected', PARAM_RAW);
1494 if ($confirm == md5($deleteselected)) {
1495 if ($questionlist = explode(',', $deleteselected)) {
1496 // for each question either hide it if it is in use or delete it
1497 foreach ($questionlist as $questionid) {
1498 $questionid = (int)$questionid;
1499 question_require_capability_on($questionid, 'edit');
1500 if (questions_in_use(array($questionid))) {
1501 $DB->set_field('question', 'hidden', 1, array('id' => $questionid));
1503 question_delete_question($questionid);
1507 redirect($this->baseurl);
1509 print_error('invalidconfirm', 'question');
1514 // Unhide a question
1515 if(($unhide = optional_param('unhide', '', PARAM_INT)) and confirm_sesskey()) {
1516 question_require_capability_on($unhide, 'edit');
1517 $DB->set_field('question', 'hidden', 0, array('id' => $unhide));
1518 redirect($this->baseurl);
1522 public function process_actions_needing_ui() {
1523 global $DB, $OUTPUT;
1524 if (optional_param('deleteselected', false, PARAM_BOOL)) {
1525 // make a list of all the questions that are selected
1526 $rawquestions = $_REQUEST; // This code is called by both POST forms and GET links, so cannot use data_submitted.
1527 $questionlist = ''; // comma separated list of ids of questions to be deleted
1528 $questionnames = ''; // string with names of questions separated by <br /> with
1529 // an asterix in front of those that are in use
1530 $inuse = false; // set to true if at least one of the questions is in use
1531 foreach ($rawquestions as $key => $value) { // Parse input for question ids
1532 if (preg_match('!^q([0-9]+)$!', $key, $matches)) {
1534 $questionlist .= $key.',';
1535 question_require_capability_on($key, 'edit');
1536 if (questions_in_use(array($key))) {
1537 $questionnames .= '* ';
1540 $questionnames .= $DB->get_field('question', 'name', array('id' => $key)) . '<br />';
1543 if (!$questionlist) { // no questions were selected
1544 redirect($this->baseurl);
1546 $questionlist = rtrim($questionlist, ',');
1548 // Add an explanation about questions in use
1550 $questionnames .= '<br />'.get_string('questionsinuse', 'question');
1552 $baseurl = new moodle_url('edit.php', $this->baseurl->params());
1553 $deleteurl = new moodle_url($baseurl, array('deleteselected'=>$questionlist, 'confirm'=>md5($questionlist), 'sesskey'=>sesskey()));
1555 echo $OUTPUT->confirm(get_string('deletequestionscheck', 'question', $questionnames), $deleteurl, $baseurl);
1563 * Common setup for all pages for editing questions.
1564 * @param string $baseurl the name of the script calling this funciton. For examle 'qusetion/edit.php'.
1565 * @param string $edittab code for this edit tab
1566 * @param bool $requirecmid require cmid? default false
1567 * @param bool $requirecourseid require courseid, if cmid is not given? default true
1568 * @return array $thispageurl, $contexts, $cmid, $cm, $module, $pagevars
1570 function question_edit_setup($edittab, $baseurl, $requirecmid = false, $requirecourseid = true) {
1573 $thispageurl = new moodle_url($baseurl);
1574 $thispageurl->remove_all_params(); // We are going to explicity add back everything important - this avoids unwanted params from being retained.
1577 $cmid =required_param('cmid', PARAM_INT);
1579 $cmid = optional_param('cmid', 0, PARAM_INT);
1582 list($module, $cm) = get_module_from_cmid($cmid);
1583 $courseid = $cm->course;
1584 $thispageurl->params(compact('cmid'));
1585 require_login($courseid, false, $cm);
1586 $thiscontext = get_context_instance(CONTEXT_MODULE, $cmid);
1590 if ($requirecourseid){
1591 $courseid = required_param('courseid', PARAM_INT);
1593 $courseid = optional_param('courseid', 0, PARAM_INT);
1596 $thispageurl->params(compact('courseid'));
1597 require_login($courseid, false);
1598 $thiscontext = get_context_instance(CONTEXT_COURSE, $courseid);
1600 $thiscontext = null;
1605 $contexts = new question_edit_contexts($thiscontext);
1606 $contexts->require_one_edit_tab_cap($edittab);
1612 $PAGE->set_pagelayout('admin');
1614 $pagevars['qpage'] = optional_param('qpage', -1, PARAM_INT);
1616 //pass 'cat' from page to page and when 'category' comes from a drop down menu
1617 //then we also reset the qpage so we go to page 1 of
1619 $pagevars['cat'] = optional_param('cat', 0, PARAM_SEQUENCE); // if empty will be set up later
1620 if ($category = optional_param('category', 0, PARAM_SEQUENCE)) {
1621 if ($pagevars['cat'] != $category) { // is this a move to a new category?
1622 $pagevars['cat'] = $category;
1623 $pagevars['qpage'] = 0;
1626 if ($pagevars['cat']){
1627 $thispageurl->param('cat', $pagevars['cat']);
1629 if (strpos($baseurl, '/question/') === 0) {
1630 navigation_node::override_active_url($thispageurl);
1633 if ($pagevars['qpage'] > -1) {
1634 $thispageurl->param('qpage', $pagevars['qpage']);
1636 $pagevars['qpage'] = 0;
1639 $pagevars['qperpage'] = optional_param('qperpage', -1, PARAM_INT);
1640 if ($pagevars['qperpage'] > -1) {
1641 $thispageurl->param('qperpage', $pagevars['qperpage']);
1643 $pagevars['qperpage'] = DEFAULT_QUESTIONS_PER_PAGE;
1646 for ($i = 1; $i <= question_bank_view::MAX_SORTS; $i++) {
1647 $param = 'qbs' . $i;
1648 if (!$sort = optional_param($param, '', PARAM_ALPHAEXT)) {
1651 $thispageurl->param($param, $sort);
1654 $defaultcategory = question_make_default_categories($contexts->all());
1656 $contextlistarr = array();
1657 foreach ($contexts->having_one_edit_tab_cap($edittab) as $context){
1658 $contextlistarr[] = "'$context->id'";
1660 $contextlist = join($contextlistarr, ' ,');
1661 if (!empty($pagevars['cat'])){
1662 $catparts = explode(',', $pagevars['cat']);
1663 if (!$catparts[0] || (false !== array_search($catparts[1], $contextlistarr)) ||
1664 !$DB->count_records_select("question_categories", "id = ? AND contextid = ?", array($catparts[0], $catparts[1]))) {
1665 print_error('invalidcategory', 'question');
1668 $category = $defaultcategory;
1669 $pagevars['cat'] = "$category->id,$category->contextid";
1672 if(($recurse = optional_param('recurse', -1, PARAM_BOOL)) != -1) {
1673 $pagevars['recurse'] = $recurse;
1674 $thispageurl->param('recurse', $recurse);
1676 $pagevars['recurse'] = 1;
1679 if(($showhidden = optional_param('showhidden', -1, PARAM_BOOL)) != -1) {
1680 $pagevars['showhidden'] = $showhidden;
1681 $thispageurl->param('showhidden', $showhidden);
1683 $pagevars['showhidden'] = 0;
1686 if(($showquestiontext = optional_param('qbshowtext', -1, PARAM_BOOL)) != -1) {
1687 $pagevars['qbshowtext'] = $showquestiontext;
1688 $thispageurl->param('qbshowtext', $showquestiontext);
1690 $pagevars['qbshowtext'] = 0;
1693 //category list page
1694 $pagevars['cpage'] = optional_param('cpage', 1, PARAM_INT);
1695 if ($pagevars['cpage'] != 1){
1696 $thispageurl->param('cpage', $pagevars['cpage']);
1699 return array($thispageurl, $contexts, $cmid, $cm, $module, $pagevars);
1703 * Make sure user is logged in as required in this context.
1705 function require_login_in_context($contextorid = null){
1707 if (!is_object($contextorid)){
1708 $context = get_context_instance_by_id($contextorid);
1710 $context = $contextorid;
1712 if ($context && ($context->contextlevel == CONTEXT_COURSE)) {
1713 require_login($context->instanceid);
1714 } else if ($context && ($context->contextlevel == CONTEXT_MODULE)) {
1715 if ($cm = $DB->get_record('course_modules',array('id' =>$context->instanceid))) {
1716 if (!$course = $DB->get_record('course', array('id' => $cm->course))) {
1717 print_error('invalidcourseid');
1719 require_course_login($course, true, $cm);
1722 print_error('invalidcoursemodule');
1724 } else if ($context && ($context->contextlevel == CONTEXT_SYSTEM)) {
1725 if (!empty($CFG->forcelogin)) {
1735 * Print a form to let the user choose which question type to add.
1736 * When the form is submitted, it goes to the question.php script.
1737 * @param $hiddenparams hidden parameters to add to the form, in addition to
1738 * the qtype radio buttons.
1740 function print_choose_qtype_to_add_form($hiddenparams) {
1741 global $CFG, $PAGE, $OUTPUT;
1742 $PAGE->requires->js('/question/qbank.js');
1743 echo '<div id="chooseqtypehead" class="hd">' . "\n";
1744 echo $OUTPUT->heading(get_string('chooseqtypetoadd', 'question'), 3);
1746 echo '<div id="chooseqtype">' . "\n";
1747 echo '<form action="' . $CFG->wwwroot . '/question/question.php" method="get"><div id="qtypeformdiv">' . "\n";
1748 foreach ($hiddenparams as $name => $value) {
1749 echo '<input type="hidden" name="' . s($name) . '" value="' . s($value) . '" />' . "\n";
1752 echo '<div class="qtypes">' . "\n";
1753 echo '<div class="instruction">' . get_string('selectaqtypefordescription', 'question') . "</div>\n";
1754 echo '<div class="realqtypes">' . "\n";
1755 $fakeqtypes = array();
1756 foreach (question_bank::get_creatable_qtypes() as $qtype) {
1757 if ($qtype->is_real_question_type()) {
1758 print_qtype_to_add_option($qtype);
1760 $fakeqtypes[] = $qtype;
1764 echo '<div class="fakeqtypes">' . "\n";
1765 foreach ($fakeqtypes as $qtype) {
1766 print_qtype_to_add_option($qtype);
1770 echo '<div class="submitbuttons">' . "\n";
1771 echo '<input type="submit" value="' . get_string('next') . '" id="chooseqtype_submit" />' . "\n";
1772 echo '<input type="submit" id="chooseqtypecancel" name="addcancel" value="' . get_string('cancel') . '" />' . "\n";
1773 echo "</div></form>\n";
1775 $PAGE->requires->js_init_call('qtype_chooser.init', array('chooseqtype'));
1779 * Private function used by the preceding one.
1780 * @param question_type $qtype the question type.
1782 function print_qtype_to_add_option($qtype) {
1783 echo '<div class="qtypeoption">' . "\n";
1784 echo '<label for="' . $qtype->plugin_name() . '">';
1785 echo '<input type="radio" name="qtype" id="' . $qtype->plugin_name() .
1786 '" value="' . $qtype->name() . '" />';
1787 echo '<span class="qtypename">';
1788 $fakequestion = new stdClass();
1789 $fakequestion->qtype = $qtype->name();
1790 echo print_question_icon($fakequestion);
1791 echo $qtype->menu_name() . '</span><span class="qtypesummary">' .
1792 get_string('pluginnamesummary', $qtype->plugin_name());
1793 echo "</span></label>\n";
1798 * Print a button for creating a new question. This will open question/addquestion.php,
1799 * which in turn goes to question/question.php before getting back to $params['returnurl']
1800 * (by default the question bank screen).
1802 * @param int $categoryid The id of the category that the new question should be added to.
1803 * @param array $params Other paramters to add to the URL. You need either $params['cmid'] or
1804 * $params['courseid'], and you should probably set $params['returnurl']
1805 * @param string $caption the text to display on the button.
1806 * @param string $tooltip a tooltip to add to the button (optional).
1807 * @param bool $disabled if true, the button will be disabled.
1809 function create_new_question_button($categoryid, $params, $caption, $tooltip = '', $disabled = false) {
1810 global $CFG, $PAGE, $OUTPUT;
1811 static $choiceformprinted = false;
1812 $params['category'] = $categoryid;
1813 $url = new moodle_url('/question/addquestion.php', $params);
1814 echo $OUTPUT->single_button($url, $caption, 'get', array('disabled'=>$disabled, 'title'=>$tooltip));
1816 $PAGE->requires->yui2_lib('dragdrop');
1817 $PAGE->requires->yui2_lib('container');
1818 if (!$choiceformprinted) {
1819 echo '<div id="qtypechoicecontainer">';
1820 print_choose_qtype_to_add_form(array());
1822 $choiceformprinted = true;