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('/question/qbank.js');
411 $PAGE->requires
->js_function_call('question_bank.init_checkbox_column', array(get_string('selectall'),
412 get_string('deselectall'), 'checkq' . $question->id
));
413 $this->firstrow
= false;
417 public function get_required_fields() {
418 return array('q.id');
424 * A column type for the name of the question type.
426 * @copyright 2009 Tim Hunt
427 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
429 class question_bank_question_type_column
extends question_bank_column_base
{
430 public function get_name() {
434 protected function get_title() {
435 return get_string('qtypeveryshort', 'question');
438 protected function get_title_tip() {
439 return get_string('questiontype', 'question');
442 protected function display_content($question, $rowclasses) {
443 echo print_question_icon($question);
446 public function get_required_fields() {
447 return array('q.qtype');
450 public function is_sortable() {
457 * A column type for the name of the question name.
459 * @copyright 2009 Tim Hunt
460 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
462 class question_bank_question_name_column
extends question_bank_column_base
{
463 protected $checkboxespresent = null;
465 public function get_name() {
466 return 'questionname';
469 protected function get_title() {
470 return get_string('question');
473 protected function label_for($question) {
474 if (is_null($this->checkboxespresent
)) {
475 $this->checkboxespresent
= $this->qbank
->has_column('checkbox');
477 if ($this->checkboxespresent
) {
478 return 'checkq' . $question->id
;
484 protected function display_content($question, $rowclasses) {
485 $labelfor = $this->label_for($question);
487 echo '<label for="' . $labelfor . '">';
489 echo format_string($question->name
);
495 public function get_required_fields() {
496 return array('q.id', 'q.name');
499 public function is_sortable() {
506 * A column type for the name of the question creator.
508 * @copyright 2009 Tim Hunt
509 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
511 class question_bank_creator_name_column
extends question_bank_column_base
{
512 public function get_name() {
513 return 'creatorname';
516 protected function get_title() {
517 return get_string('createdby', 'question');
520 protected function display_content($question, $rowclasses) {
521 if (!empty($question->creatorfirstname
) && !empty($question->creatorlastname
)) {
523 $u->firstname
= $question->creatorfirstname
;
524 $u->lastname
= $question->creatorlastname
;
529 public function get_extra_joins() {
530 return array('uc' => 'LEFT JOIN {user} uc ON uc.id = q.createdby');
533 public function get_required_fields() {
534 return array('uc.firstname AS creatorfirstname', 'uc.lastname AS creatorlastname');
537 public function is_sortable() {
539 'firstname' => array('field' => 'uc.firstname', 'title' => get_string('firstname')),
540 'lastname' => array('field' => 'uc.lastname', 'title' => get_string('lastname')),
547 * A column type for the name of the question last modifier.
549 * @copyright 2009 Tim Hunt
550 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
552 class question_bank_modifier_name_column
extends question_bank_column_base
{
553 public function get_name() {
554 return 'modifiername';
557 protected function get_title() {
558 return get_string('lastmodifiedby', 'question');
561 protected function display_content($question, $rowclasses) {
562 if (!empty($question->modifierfirstname
) && !empty($question->modifierlastname
)) {
564 $u->firstname
= $question->modifierfirstname
;
565 $u->lastname
= $question->modifierlastname
;
570 public function get_extra_joins() {
571 return array('um' => 'LEFT JOIN {user} um ON um.id = q.modifiedby');
574 public function get_required_fields() {
575 return array('um.firstname AS modifierfirstname', 'um.lastname AS modifierlastname');
578 public function is_sortable() {
580 'firstname' => array('field' => 'um.firstname', 'title' => get_string('firstname')),
581 'lastname' => array('field' => 'um.lastname', 'title' => get_string('lastname')),
588 * A base class for actions that are an icon that lets you manipulate the question in some way.
590 * @copyright 2009 Tim Hunt
591 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
593 abstract class question_bank_action_column_base
extends question_bank_column_base
{
595 protected function get_title() {
599 public function get_extra_classes() {
600 return array('iconcol');
603 protected function print_icon($icon, $title, $url) {
605 echo '<a title="' . $title . '" href="' . $url . '">
606 <img src="' . $OUTPUT->pix_url($icon) . '" class="iconsmall" alt="' . $title . '" /></a>';
609 public function get_required_fields() {
610 // createdby is required for permission checks.
611 return array('q.id', 'q.createdby');
617 * Base class for question bank columns that just contain an action icon.
619 * @copyright 2009 Tim Hunt
620 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
622 class question_bank_edit_action_column
extends question_bank_action_column_base
{
626 public function init() {
628 $this->stredit
= get_string('edit');
629 $this->strview
= get_string('view');
632 public function get_name() {
636 protected function display_content($question, $rowclasses) {
637 if (question_has_capability_on($question, 'edit')) {
638 $this->print_icon('t/edit', $this->stredit
, $this->qbank
->edit_question_url($question->id
));
639 } else if (question_has_capability_on($question, 'view')) {
640 $this->print_icon('i/info', $this->strview
, $this->qbank
->edit_question_url($question->id
));
647 * Question bank columns for the preview action icon.
649 * @copyright 2009 Tim Hunt
650 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
652 class question_bank_preview_action_column
extends question_bank_action_column_base
{
653 protected $strpreview;
655 public function init() {
657 $this->strpreview
= get_string('preview');
660 public function get_name() {
661 return 'previewaction';
664 protected function display_content($question, $rowclasses) {
666 if (question_has_capability_on($question, 'use')) {
668 $image = $OUTPUT->pix_icon('t/preview', $this->strpreview
);
670 $link = $this->qbank
->preview_question_url($question);
671 $action = new popup_action('click', $link, 'questionpreview',
672 question_preview_popup_params());
674 echo $OUTPUT->action_link($link, $image, $action, array('title' => $this->strpreview
));
678 public function get_required_fields() {
679 return array('q.id');
685 * Question bank columns for the move action icon.
687 * @copyright 2009 Tim Hunt
688 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
690 class question_bank_move_action_column
extends question_bank_action_column_base
{
693 public function init() {
695 $this->strmove
= get_string('move');
698 public function get_name() {
702 protected function display_content($question, $rowclasses) {
703 if (question_has_capability_on($question, 'move')) {
704 $this->print_icon('t/move', $this->strmove
, $this->qbank
->move_question_url($question->id
));
711 * action to delete (or hide) a question, or restore a previously hidden question.
713 * @copyright 2009 Tim Hunt
714 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
716 class question_bank_delete_action_column
extends question_bank_action_column_base
{
717 protected $strdelete;
718 protected $strrestore;
720 public function init() {
722 $this->strdelete
= get_string('delete');
723 $this->strrestore
= get_string('restore');
726 public function get_name() {
727 return 'deleteaction';
730 protected function display_content($question, $rowclasses) {
731 if (question_has_capability_on($question, 'edit')) {
732 if ($question->hidden
) {
733 $url = new moodle_url($this->qbank
->base_url(), array('unhide' => $question->id
, 'sesskey'=>sesskey()));
734 $this->print_icon('t/restore', $this->strrestore
, $url);
736 $url = new moodle_url($this->qbank
->base_url(), array('deleteselected' => $question->id
, 'q' . $question->id
=> 1, 'sesskey'=>sesskey()));
737 $this->print_icon('t/delete', $this->strdelete
, $url);
742 public function get_required_fields() {
743 return array('q.id', 'q.hidden');
748 * Base class for 'columns' that are actually displayed as a row following the main question row.
750 * @copyright 2009 Tim Hunt
751 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
753 abstract class question_bank_row_base
extends question_bank_column_base
{
754 public function is_extra_row() {
758 protected function display_start($question, $rowclasses) {
760 echo '<tr class="' . $rowclasses . '">' . "\n";
764 echo '<td colspan="' . $this->qbank
->get_column_count() . '" class="' . $this->get_name() . '">';
767 protected function display_end($question, $rowclasses) {
773 * A column type for the name of the question name.
775 * @copyright 2009 Tim Hunt
776 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
778 class question_bank_question_text_row
extends question_bank_row_base
{
779 protected $formatoptions;
781 protected function init() {
782 $this->formatoptions
= new stdClass();
783 $this->formatoptions
->noclean
= true;
784 $this->formatoptions
->para
= false;
787 public function get_name() {
788 return 'questiontext';
791 protected function get_title() {
792 return get_string('questiontext', 'question');
795 protected function display_content($question, $rowclasses) {
796 $text = question_rewrite_questiontext_preview_urls($question->questiontext
,
797 $question->contextid
, 'question', $question->id
);
798 $text = format_text($text, $question->questiontextformat
,
799 $this->formatoptions
);
806 public function get_extra_joins() {
807 return array('qc' => 'JOIN {question_categories} qc ON qc.id = q.category');
810 public function get_required_fields() {
811 return array('q.id', 'q.questiontext', 'q.questiontextformat', 'qc.contextid');
816 * This class prints a view of the question bank, including
817 * + Some controls to allow users to to select what is displayed.
818 * + A list of questions as a table.
819 * + Further controls to do things with the questions.
821 * This class gives a basic view, and provides plenty of hooks where subclasses
822 * can override parts of the display.
824 * The list of questions presented as a table is generated by creating a list of
825 * question_bank_column objects, one for each 'column' to be displayed. These
827 * + outputting the contents of that column, given a $question object, but also
828 * + generating the right fragments of SQL to ensure the necessary data is present,
829 * and sorted in the right order.
830 * + outputting table headers.
832 * @copyright 2009 Tim Hunt
833 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
835 class question_bank_view
{
839 protected $editquestionurl;
840 protected $quizorcourseid;
844 protected $knowncolumntypes;
845 protected $visiblecolumns;
846 protected $extrarows;
847 protected $requiredcolumns;
849 protected $lastchangedid;
852 protected $sqlparams;
856 * @param question_edit_contexts $contexts
857 * @param moodle_url $pageurl
858 * @param object $course course settings
859 * @param object $cm (optional) activity settings.
861 public function __construct($contexts, $pageurl, $course, $cm = null) {
864 $this->contexts
= $contexts;
865 $this->baseurl
= $pageurl;
866 $this->course
= $course;
869 if (!empty($cm) && $cm->modname
== 'quiz') {
870 $this->quizorcourseid
= '&quizid=' . $cm->instance
;
872 $this->quizorcourseid
= '&courseid=' .$this->course
->id
;
875 // Create the url of the new question page to forward to.
876 $returnurl = $pageurl->out_as_local_url(false);
877 $this->editquestionurl
= new moodle_url('/question/question.php',
878 array('returnurl' => $returnurl));
880 $this->editquestionurl
->param('cmid', $cm->id
);
882 $this->editquestionurl
->param('courseid', $this->course
->id
);
885 $this->lastchangedid
= optional_param('lastchanged',0,PARAM_INT
);
887 $this->init_column_types();
888 $this->init_columns($this->wanted_columns());
891 $PAGE->requires
->yui2_lib('container');
894 protected function wanted_columns() {
895 $columns = array('checkbox', 'qtype', 'questionname', 'editaction',
896 'previewaction', 'moveaction', 'deleteaction', 'creatorname',
898 if (optional_param('qbshowtext', false, PARAM_BOOL
)) {
899 $columns[] = 'questiontext';
904 protected function known_field_types() {
906 new question_bank_checkbox_column($this),
907 new question_bank_question_type_column($this),
908 new question_bank_question_name_column($this),
909 new question_bank_creator_name_column($this),
910 new question_bank_modifier_name_column($this),
911 new question_bank_edit_action_column($this),
912 new question_bank_preview_action_column($this),
913 new question_bank_move_action_column($this),
914 new question_bank_delete_action_column($this),
915 new question_bank_question_text_row($this),
919 protected function init_column_types() {
920 $this->knowncolumntypes
= array();
921 foreach ($this->known_field_types() as $col) {
922 $this->knowncolumntypes
[$col->get_name()] = $col;
926 protected function init_columns($wanted) {
927 $this->visiblecolumns
= array();
928 $this->extrarows
= array();
929 foreach ($wanted as $colname) {
930 if (!isset($this->knowncolumntypes
[$colname])) {
931 throw new coding_exception('Unknown column type ' . $colname . ' requested in init columns.');
933 $column = $this->knowncolumntypes
[$colname];
934 if ($column->is_extra_row()) {
935 $this->extrarows
[$colname] = $column;
937 $this->visiblecolumns
[$colname] = $column;
940 $this->requiredcolumns
= array_merge($this->visiblecolumns
, $this->extrarows
);
944 * @param string $colname a column internal name.
945 * @return bool is this column included in the output?
947 public function has_column($colname) {
948 return isset($this->visiblecolumns
[$colname]);
952 * @return int The number of columns in the table.
954 public function get_column_count() {
955 return count($this->visiblecolumns
);
958 public function get_courseid() {
959 return $this->course
->id
;
962 protected function init_sort() {
963 $this->init_sort_from_params();
964 if (empty($this->sort
)) {
965 $this->sort
= $this->default_sort();
970 * Deal with a sort name of the form columnname, or colname_subsort by
971 * breaking it up, validating the bits that are presend, and returning them.
972 * If there is no subsort, then $subsort is returned as ''.
973 * @return array array($colname, $subsort).
975 protected function parse_subsort($sort) {
977 if (strpos($sort, '_') !== false) {
978 list($colname, $subsort) = explode('_', $sort, 2);
983 /// Validate the column name.
984 if (!isset($this->knowncolumntypes
[$colname]) ||
!$this->knowncolumntypes
[$colname]->is_sortable()) {
985 for ($i = 1; $i <= question_bank_view
::MAX_SORTS
; $i++
) {
986 $this->baseurl
->remove_params('qbs' . $i);
988 throw new moodle_exception('unknownsortcolumn', '', $link = $this->baseurl
->out(), $colname);
990 /// Validate the subsort, if present.
992 $subsorts = $this->knowncolumntypes
[$colname]->is_sortable();
993 if (!is_array($subsorts) ||
!isset($subsorts[$subsort])) {
994 throw new moodle_exception('unknownsortcolumn', '', $link = $this->baseurl
->out(), $sort);
997 return array($colname, $subsort);
1000 protected function init_sort_from_params() {
1001 $this->sort
= array();
1002 for ($i = 1; $i <= question_bank_view
::MAX_SORTS
; $i++
) {
1003 if (!$sort = optional_param('qbs' . $i, '', PARAM_ALPHAEXT
)) {
1006 // Work out the appropriate order.
1008 if ($sort[0] == '-') {
1010 $sort = substr($sort, 1);
1015 // Deal with subsorts.
1016 list($colname, $subsort) = $this->parse_subsort($sort);
1017 $this->requiredcolumns
[$colname] = $this->knowncolumntypes
[$colname];
1018 $this->sort
[$sort] = $order;
1022 protected function sort_to_params($sorts) {
1025 foreach ($sorts as $sort => $order) {
1028 $sort = '-' . $sort;
1030 $params['qbs' . $i] = $sort;
1035 protected function default_sort() {
1036 $this->requiredcolumns
['qtype'] = $this->knowncolumntypes
['qtype'];
1037 $this->requiredcolumns
['questionname'] = $this->knowncolumntypes
['questionname'];
1038 return array('qtype' => 1, 'questionname' => 1);
1042 * @param $sort a column or column_subsort name.
1043 * @return int the current sort order for this column -1, 0, 1
1045 public function get_primary_sort_order($sort) {
1046 $order = reset($this->sort
);
1047 $primarysort = key($this->sort
);
1048 if ($sort == $primarysort) {
1056 * Get a URL to redisplay the page with a new sort for the question bank.
1057 * @param string $sort the column, or column_subsort to sort on.
1058 * @param bool $newsortreverse whether to sort in reverse order.
1059 * @return string The new URL.
1061 public function new_sort_url($sort, $newsortreverse) {
1062 if ($newsortreverse) {
1067 // Tricky code to add the new sort at the start, removing it from where it was before, if it was present.
1068 $newsort = array_reverse($this->sort
);
1069 if (isset($newsort[$sort])) {
1070 unset($newsort[$sort]);
1072 $newsort[$sort] = $order;
1073 $newsort = array_reverse($newsort);
1074 if (count($newsort) > question_bank_view
::MAX_SORTS
) {
1075 $newsort = array_slice($newsort, 0, question_bank_view
::MAX_SORTS
, true);
1077 return $this->baseurl
->out(true, $this->sort_to_params($newsort));
1080 protected function build_query_sql($category, $recurse, $showhidden) {
1083 /// Get the required tables.
1085 foreach ($this->requiredcolumns
as $column) {
1086 $extrajoins = $column->get_extra_joins();
1087 foreach ($extrajoins as $prefix => $join) {
1088 if (isset($joins[$prefix]) && $joins[$prefix] != $join) {
1089 throw new coding_exception('Join ' . $join . ' conflicts with previous join ' . $joins[$prefix]);
1091 $joins[$prefix] = $join;
1095 /// Get the required fields.
1096 $fields = array('q.hidden', 'q.category');
1097 foreach ($this->visiblecolumns
as $column) {
1098 $fields = array_merge($fields, $column->get_required_fields());
1100 foreach ($this->extrarows
as $row) {
1101 $fields = array_merge($fields, $row->get_required_fields());
1103 $fields = array_unique($fields);
1105 /// Build the order by clause.
1107 foreach ($this->sort
as $sort => $order) {
1108 list($colname, $subsort) = $this->parse_subsort($sort);
1109 $sorts[] = $this->requiredcolumns
[$colname]->sort_expression($order < 0, $subsort);
1112 /// Build the where clause.
1113 $tests = array('q.parent = 0');
1116 $tests[] = 'q.hidden = 0';
1120 $categoryids = question_categorylist($category->id
);
1122 $categoryids = array($category->id
);
1124 list($catidtest, $params) = $DB->get_in_or_equal($categoryids, SQL_PARAMS_NAMED
, 'cat');
1125 $tests[] = 'q.category ' . $catidtest;
1126 $this->sqlparams
= $params;
1129 $sql = ' FROM {question} q ' . implode(' ', $joins);
1130 $sql .= ' WHERE ' . implode(' AND ', $tests);
1131 $this->countsql
= 'SELECT count(1)' . $sql;
1132 $this->loadsql
= 'SELECT ' . implode(', ', $fields) . $sql . ' ORDER BY ' . implode(', ', $sorts);
1133 $this->sqlparams
= $params;
1136 protected function get_question_count() {
1138 return $DB->count_records_sql($this->countsql
, $this->sqlparams
);
1141 protected function load_page_questions($page, $perpage) {
1143 $questions = $DB->get_recordset_sql($this->loadsql
, $this->sqlparams
, $page*$perpage, $perpage);
1144 if (!$questions->valid()) {
1145 /// No questions on this page. Reset to page 0.
1146 $questions = $DB->get_recordset_sql($this->loadsql
, $this->sqlparams
, 0, $perpage);
1151 public function base_url() {
1152 return $this->baseurl
;
1155 public function edit_question_url($questionid) {
1156 return $this->editquestionurl
->out(true, array('id' => $questionid));
1159 public function move_question_url($questionid) {
1160 return $this->editquestionurl
->out(true, array('id' => $questionid, 'movecontext' => 1));
1163 public function preview_question_url($question) {
1164 return question_preview_url($question->id
, null, null, null, null,
1165 $this->contexts
->lowest());
1169 * Shows the question bank editing interface.
1171 * The function also processes a number of actions:
1173 * Actions affecting the question pool:
1174 * move Moves a question to a different category
1175 * deleteselected Deletes the selected questions from the category
1177 * category Chooses the category
1178 * displayoptions Sets display options
1180 public function display($tabname, $page, $perpage, $cat,
1181 $recurse, $showhidden, $showquestiontext) {
1182 global $PAGE, $OUTPUT;
1184 if ($this->process_actions_needing_ui()) {
1188 $PAGE->requires
->js('/question/qbank.js');
1190 // Category selection form
1191 echo $OUTPUT->heading(get_string('questionbank', 'question'), 2);
1193 $this->display_category_form($this->contexts
->having_one_edit_tab_cap($tabname),
1194 $this->baseurl
, $cat);
1195 $this->display_options($recurse, $showhidden, $showquestiontext);
1197 if (!$category = $this->get_current_category($cat)) {
1200 $this->print_category_info($category);
1202 // continues with list of questions
1203 $this->display_question_list($this->contexts
->having_one_edit_tab_cap($tabname),
1204 $this->baseurl
, $cat, $this->cm
,
1205 $recurse, $page, $perpage, $showhidden, $showquestiontext,
1206 $this->contexts
->having_cap('moodle/question:add'));
1209 protected function print_choose_category_message($categoryandcontext) {
1210 echo "<p style=\"text-align:center;\"><b>";
1211 print_string('selectcategoryabove', 'question');
1215 protected function get_current_category($categoryandcontext) {
1216 global $DB, $OUTPUT;
1217 list($categoryid, $contextid) = explode(',', $categoryandcontext);
1219 $this->print_choose_category_message($categoryandcontext);
1223 if (!$category = $DB->get_record('question_categories',
1224 array('id' => $categoryid, 'contextid' => $contextid))) {
1225 echo $OUTPUT->box_start('generalbox questionbank');
1226 echo $OUTPUT->notification('Category not found!');
1227 echo $OUTPUT->box_end();
1234 protected function print_category_info($category) {
1235 $formatoptions = new stdClass();
1236 $formatoptions->noclean
= true;
1237 $formatoptions->overflowdiv
= true;
1238 echo '<div class="boxaligncenter">';
1239 echo format_text($category->info
, $category->infoformat
, $formatoptions, $this->course
->id
);
1244 * prints a form to choose categories
1246 protected function display_category_form($contexts, $pageurl, $current) {
1247 global $CFG, $OUTPUT;
1249 /// Get all the existing categories now
1250 echo '<div class="choosecategory">';
1251 $catmenu = question_category_options($contexts, false, 0, true);
1253 $select = new single_select($this->baseurl
, 'category', $catmenu, $current, null, 'catmenu');
1254 $select->set_label(get_string('selectacategory', 'question'));
1255 echo $OUTPUT->render($select);
1259 protected function display_options($recurse, $showhidden, $showquestiontext) {
1260 echo '<form method="get" action="edit.php" id="displayoptions">';
1261 echo "<fieldset class='invisiblefieldset'>";
1262 echo html_writer
::input_hidden_params($this->baseurl
, array('recurse', 'showhidden', 'qbshowtext'));
1263 $this->display_category_form_checkbox('recurse', $recurse, get_string('includesubcategories', 'question'));
1264 $this->display_category_form_checkbox('showhidden', $showhidden, get_string('showhidden', 'question'));
1265 $this->display_category_form_checkbox('qbshowtext', $showquestiontext, get_string('showquestiontext', 'question'));
1266 echo '<noscript><div class="centerpara"><input type="submit" value="'. get_string('go') .'" />';
1267 echo '</div></noscript></fieldset></form>';
1271 * Print a single option checkbox. Used by the preceeding.
1273 protected function display_category_form_checkbox($name, $value, $label) {
1274 echo '<div><input type="hidden" id="' . $name . '_off" name="' . $name . '" value="0" />';
1275 echo '<input type="checkbox" id="' . $name . '_on" name="' . $name . '" value="1"';
1277 echo ' checked="checked"';
1279 echo ' onchange="getElementById(\'displayoptions\').submit(); return true;" />';
1280 echo '<label for="' . $name . '_on">' . $label . '</label>';
1284 protected function create_new_question_form($category, $canadd) {
1286 echo '<div class="createnewquestion">';
1288 create_new_question_button($category->id
, $this->editquestionurl
->params(),
1289 get_string('createnewquestion', 'question'));
1291 print_string('nopermissionadd', 'question');
1297 * Prints the table of questions in a category with interactions
1299 * @param object $course The course object
1300 * @param int $categoryid The id of the question category to be displayed
1301 * @param int $cm The course module record if we are in the context of a particular module, 0 otherwise
1302 * @param int $recurse This is 1 if subcategories should be included, 0 otherwise
1303 * @param int $page The number of the page to be displayed
1304 * @param int $perpage Number of questions to show per page
1305 * @param bool $showhidden True if also hidden questions should be displayed
1306 * @param bool $showquestiontext whether the text of each question should be shown in the list
1308 protected function display_question_list($contexts, $pageurl, $categoryandcontext,
1309 $cm = null, $recurse=1, $page=0, $perpage=100, $showhidden=false,
1310 $showquestiontext = false, $addcontexts = array()) {
1311 global $CFG, $DB, $OUTPUT;
1313 $category = $this->get_current_category($categoryandcontext);
1315 $cmoptions = new stdClass();
1316 $cmoptions->hasattempts
= !empty($this->quizhasattempts
);
1318 $strselectall = get_string('selectall');
1319 $strselectnone = get_string('deselectall');
1320 $strdelete = get_string('delete');
1322 list($categoryid, $contextid) = explode(',', $categoryandcontext);
1323 $catcontext = get_context_instance_by_id($contextid);
1325 $canadd = has_capability('moodle/question:add', $catcontext);
1326 $caneditall =has_capability('moodle/question:editall', $catcontext);
1327 $canuseall =has_capability('moodle/question:useall', $catcontext);
1328 $canmoveall =has_capability('moodle/question:moveall', $catcontext);
1330 $this->create_new_question_form($category, $canadd);
1332 $this->build_query_sql($category, $recurse, $showhidden);
1333 $totalnumber = $this->get_question_count();
1334 if ($totalnumber == 0) {
1338 $questions = $this->load_page_questions($page, $perpage);
1340 echo '<div class="categorypagingbarcontainer">';
1341 $pageing_url = new moodle_url('edit.php');
1342 $r = $pageing_url->params($pageurl->params());
1343 $pagingbar = new paging_bar($totalnumber, $page, $perpage, $pageing_url);
1344 $pagingbar->pagevar
= 'qpage';
1345 echo $OUTPUT->render($pagingbar);
1348 echo '<form method="post" action="edit.php">';
1349 echo '<fieldset class="invisiblefieldset" style="display: block;">';
1350 echo '<input type="hidden" name="sesskey" value="'.sesskey().'" />';
1351 echo html_writer
::input_hidden_params($pageurl);
1353 echo '<div class="categoryquestionscontainer">';
1354 $this->start_table();
1356 foreach ($questions as $question) {
1357 $this->print_table_row($question, $rowcount);
1363 echo '<div class="categorypagingbarcontainer pagingbottom">';
1364 echo $OUTPUT->render($pagingbar);
1365 if ($totalnumber > DEFAULT_QUESTIONS_PER_PAGE
) {
1366 if ($perpage == DEFAULT_QUESTIONS_PER_PAGE
) {
1367 $url = new moodle_url('edit.php', array_merge($pageurl->params(), array('qperpage'=>1000)));
1368 $showall = '<a href="'.$url.'">'.get_string('showall', 'moodle', $totalnumber).'</a>';
1370 $url = new moodle_url('edit.php', array_merge($pageurl->params(), array('qperpage'=>DEFAULT_QUESTIONS_PER_PAGE
)));
1371 $showall = '<a href="'.$url.'">'.get_string('showperpage', 'moodle', DEFAULT_QUESTIONS_PER_PAGE
).'</a>';
1373 echo "<div class='paging'>$showall</div>";
1377 echo '<div class="modulespecificbuttonscontainer">';
1378 if ($caneditall ||
$canmoveall ||
$canuseall){
1379 echo '<strong> '.get_string('withselected', 'question').':</strong><br />';
1381 if (function_exists('module_specific_buttons')) {
1382 echo module_specific_buttons($this->cm
->id
,$cmoptions);
1385 // print delete and move selected question
1387 echo '<input type="submit" name="deleteselected" value="' . $strdelete . "\" />\n";
1390 if ($canmoveall && count($addcontexts)) {
1391 echo '<input type="submit" name="move" value="'.get_string('moveto', 'question')."\" />\n";
1392 question_category_select_menu($addcontexts, false, 0, "$category->id,$category->contextid");
1395 if (function_exists('module_specific_controls') && $canuseall) {
1396 $modulespecific = module_specific_controls($totalnumber, $recurse, $category, $this->cm
->id
,$cmoptions);
1397 if(!empty($modulespecific)){
1398 echo "<hr />$modulespecific";
1408 protected function start_table() {
1409 echo '<table id="categoryquestions">' . "\n";
1411 $this->print_table_headers();
1416 protected function end_table() {
1421 protected function print_table_headers() {
1423 foreach ($this->visiblecolumns
as $column) {
1424 $column->display_header();
1429 protected function get_row_classes($question, $rowcount) {
1431 if ($question->hidden
) {
1432 $classes[] = 'dimmed_text';
1434 if ($question->id
== $this->lastchangedid
) {
1435 $classes[] ='highlight';
1437 $classes[] = 'r' . ($rowcount %
2);
1441 protected function print_table_row($question, $rowcount) {
1442 $rowclasses = implode(' ', $this->get_row_classes($question, $rowcount));
1444 echo '<tr class="' . $rowclasses . '">' . "\n";
1448 foreach ($this->visiblecolumns
as $column) {
1449 $column->display($question, $rowclasses);
1452 foreach ($this->extrarows
as $row) {
1453 $row->display($question, $rowclasses);
1457 public function process_actions() {
1459 /// Now, check for commands on this page and modify variables as necessary
1460 if (optional_param('move', false, PARAM_BOOL
) and confirm_sesskey()) {
1461 // Move selected questions to new category
1462 $category = required_param('category', PARAM_SEQUENCE
);
1463 list($tocategoryid, $contextid) = explode(',', $category);
1464 if (! $tocategory = $DB->get_record('question_categories', array('id' => $tocategoryid, 'contextid' => $contextid))) {
1465 print_error('cannotfindcate', 'question');
1467 $tocontext = get_context_instance_by_id($contextid);
1468 require_capability('moodle/question:add', $tocontext);
1469 $rawdata = (array) data_submitted();
1470 $questionids = array();
1471 foreach ($rawdata as $key => $value) { // Parse input for question ids
1472 if (preg_match('!^q([0-9]+)$!', $key, $matches)) {
1474 $questionids[] = $key;
1478 list($usql, $params) = $DB->get_in_or_equal($questionids);
1480 $questions = $DB->get_records_sql("
1481 SELECT q.*, c.contextid
1483 JOIN {question_categories} c ON c.id = q.category
1484 WHERE q.id $usql", $params);
1485 foreach ($questions as $question){
1486 question_require_capability_on($question, 'move');
1488 question_move_questions_to_category($questionids, $tocategory->id
);
1489 redirect($this->baseurl
->out(false,
1490 array('category' => "$tocategoryid,$contextid")));
1494 if (optional_param('deleteselected', false, PARAM_BOOL
)) { // delete selected questions from the category
1495 if (($confirm = optional_param('confirm', '', PARAM_ALPHANUM
)) and confirm_sesskey()) { // teacher has already confirmed the action
1496 $deleteselected = required_param('deleteselected', PARAM_RAW
);
1497 if ($confirm == md5($deleteselected)) {
1498 if ($questionlist = explode(',', $deleteselected)) {
1499 // for each question either hide it if it is in use or delete it
1500 foreach ($questionlist as $questionid) {
1501 $questionid = (int)$questionid;
1502 question_require_capability_on($questionid, 'edit');
1503 if (questions_in_use(array($questionid))) {
1504 $DB->set_field('question', 'hidden', 1, array('id' => $questionid));
1506 question_delete_question($questionid);
1510 redirect($this->baseurl
);
1512 print_error('invalidconfirm', 'question');
1517 // Unhide a question
1518 if(($unhide = optional_param('unhide', '', PARAM_INT
)) and confirm_sesskey()) {
1519 question_require_capability_on($unhide, 'edit');
1520 $DB->set_field('question', 'hidden', 0, array('id' => $unhide));
1521 redirect($this->baseurl
);
1525 public function process_actions_needing_ui() {
1526 global $DB, $OUTPUT;
1527 if (optional_param('deleteselected', false, PARAM_BOOL
)) {
1528 // make a list of all the questions that are selected
1529 $rawquestions = $_REQUEST; // This code is called by both POST forms and GET links, so cannot use data_submitted.
1530 $questionlist = ''; // comma separated list of ids of questions to be deleted
1531 $questionnames = ''; // string with names of questions separated by <br /> with
1532 // an asterix in front of those that are in use
1533 $inuse = false; // set to true if at least one of the questions is in use
1534 foreach ($rawquestions as $key => $value) { // Parse input for question ids
1535 if (preg_match('!^q([0-9]+)$!', $key, $matches)) {
1537 $questionlist .= $key.',';
1538 question_require_capability_on($key, 'edit');
1539 if (questions_in_use(array($key))) {
1540 $questionnames .= '* ';
1543 $questionnames .= $DB->get_field('question', 'name', array('id' => $key)) . '<br />';
1546 if (!$questionlist) { // no questions were selected
1547 redirect($this->baseurl
);
1549 $questionlist = rtrim($questionlist, ',');
1551 // Add an explanation about questions in use
1553 $questionnames .= '<br />'.get_string('questionsinuse', 'question');
1555 $baseurl = new moodle_url('edit.php', $this->baseurl
->params());
1556 $deleteurl = new moodle_url($baseurl, array('deleteselected'=>$questionlist, 'confirm'=>md5($questionlist), 'sesskey'=>sesskey()));
1558 echo $OUTPUT->confirm(get_string('deletequestionscheck', 'question', $questionnames), $deleteurl, $baseurl);
1566 * Common setup for all pages for editing questions.
1567 * @param string $baseurl the name of the script calling this funciton. For examle 'qusetion/edit.php'.
1568 * @param string $edittab code for this edit tab
1569 * @param bool $requirecmid require cmid? default false
1570 * @param bool $requirecourseid require courseid, if cmid is not given? default true
1571 * @return array $thispageurl, $contexts, $cmid, $cm, $module, $pagevars
1573 function question_edit_setup($edittab, $baseurl, $requirecmid = false, $requirecourseid = true) {
1576 $thispageurl = new moodle_url($baseurl);
1577 $thispageurl->remove_all_params(); // We are going to explicity add back everything important - this avoids unwanted params from being retained.
1580 $cmid =required_param('cmid', PARAM_INT
);
1582 $cmid = optional_param('cmid', 0, PARAM_INT
);
1585 list($module, $cm) = get_module_from_cmid($cmid);
1586 $courseid = $cm->course
;
1587 $thispageurl->params(compact('cmid'));
1588 require_login($courseid, false, $cm);
1589 $thiscontext = get_context_instance(CONTEXT_MODULE
, $cmid);
1593 if ($requirecourseid){
1594 $courseid = required_param('courseid', PARAM_INT
);
1596 $courseid = optional_param('courseid', 0, PARAM_INT
);
1599 $thispageurl->params(compact('courseid'));
1600 require_login($courseid, false);
1601 $thiscontext = get_context_instance(CONTEXT_COURSE
, $courseid);
1603 $thiscontext = null;
1608 $contexts = new question_edit_contexts($thiscontext);
1609 $contexts->require_one_edit_tab_cap($edittab);
1615 $PAGE->set_pagelayout('admin');
1617 $pagevars['qpage'] = optional_param('qpage', -1, PARAM_INT
);
1619 //pass 'cat' from page to page and when 'category' comes from a drop down menu
1620 //then we also reset the qpage so we go to page 1 of
1622 $pagevars['cat'] = optional_param('cat', 0, PARAM_SEQUENCE
); // if empty will be set up later
1623 if ($category = optional_param('category', 0, PARAM_SEQUENCE
)) {
1624 if ($pagevars['cat'] != $category) { // is this a move to a new category?
1625 $pagevars['cat'] = $category;
1626 $pagevars['qpage'] = 0;
1629 if ($pagevars['cat']){
1630 $thispageurl->param('cat', $pagevars['cat']);
1632 if (strpos($baseurl, '/question/') === 0) {
1633 navigation_node
::override_active_url($thispageurl);
1636 if ($pagevars['qpage'] > -1) {
1637 $thispageurl->param('qpage', $pagevars['qpage']);
1639 $pagevars['qpage'] = 0;
1642 $pagevars['qperpage'] = optional_param('qperpage', -1, PARAM_INT
);
1643 if ($pagevars['qperpage'] > -1) {
1644 $thispageurl->param('qperpage', $pagevars['qperpage']);
1646 $pagevars['qperpage'] = DEFAULT_QUESTIONS_PER_PAGE
;
1649 for ($i = 1; $i <= question_bank_view
::MAX_SORTS
; $i++
) {
1650 $param = 'qbs' . $i;
1651 if (!$sort = optional_param($param, '', PARAM_ALPHAEXT
)) {
1654 $thispageurl->param($param, $sort);
1657 $defaultcategory = question_make_default_categories($contexts->all());
1659 $contextlistarr = array();
1660 foreach ($contexts->having_one_edit_tab_cap($edittab) as $context){
1661 $contextlistarr[] = "'$context->id'";
1663 $contextlist = join($contextlistarr, ' ,');
1664 if (!empty($pagevars['cat'])){
1665 $catparts = explode(',', $pagevars['cat']);
1666 if (!$catparts[0] ||
(false !== array_search($catparts[1], $contextlistarr)) ||
1667 !$DB->count_records_select("question_categories", "id = ? AND contextid = ?", array($catparts[0], $catparts[1]))) {
1668 print_error('invalidcategory', 'question');
1671 $category = $defaultcategory;
1672 $pagevars['cat'] = "$category->id,$category->contextid";
1675 if(($recurse = optional_param('recurse', -1, PARAM_BOOL
)) != -1) {
1676 $pagevars['recurse'] = $recurse;
1677 $thispageurl->param('recurse', $recurse);
1679 $pagevars['recurse'] = 1;
1682 if(($showhidden = optional_param('showhidden', -1, PARAM_BOOL
)) != -1) {
1683 $pagevars['showhidden'] = $showhidden;
1684 $thispageurl->param('showhidden', $showhidden);
1686 $pagevars['showhidden'] = 0;
1689 if(($showquestiontext = optional_param('qbshowtext', -1, PARAM_BOOL
)) != -1) {
1690 $pagevars['qbshowtext'] = $showquestiontext;
1691 $thispageurl->param('qbshowtext', $showquestiontext);
1693 $pagevars['qbshowtext'] = 0;
1696 //category list page
1697 $pagevars['cpage'] = optional_param('cpage', 1, PARAM_INT
);
1698 if ($pagevars['cpage'] != 1){
1699 $thispageurl->param('cpage', $pagevars['cpage']);
1702 return array($thispageurl, $contexts, $cmid, $cm, $module, $pagevars);
1706 * Make sure user is logged in as required in this context.
1708 function require_login_in_context($contextorid = null){
1710 if (!is_object($contextorid)){
1711 $context = get_context_instance_by_id($contextorid);
1713 $context = $contextorid;
1715 if ($context && ($context->contextlevel
== CONTEXT_COURSE
)) {
1716 require_login($context->instanceid
);
1717 } else if ($context && ($context->contextlevel
== CONTEXT_MODULE
)) {
1718 if ($cm = $DB->get_record('course_modules',array('id' =>$context->instanceid
))) {
1719 if (!$course = $DB->get_record('course', array('id' => $cm->course
))) {
1720 print_error('invalidcourseid');
1722 require_course_login($course, true, $cm);
1725 print_error('invalidcoursemodule');
1727 } else if ($context && ($context->contextlevel
== CONTEXT_SYSTEM
)) {
1728 if (!empty($CFG->forcelogin
)) {
1738 * Print a form to let the user choose which question type to add.
1739 * When the form is submitted, it goes to the question.php script.
1740 * @param $hiddenparams hidden parameters to add to the form, in addition to
1741 * the qtype radio buttons.
1742 * @param $allowedqtypes optional list of qtypes that are allowed. If given, only
1743 * those qtypes will be shown. Example value array('description', 'multichoice').
1745 function print_choose_qtype_to_add_form($hiddenparams, array $allowedqtypes = null) {
1746 global $CFG, $PAGE, $OUTPUT;
1747 $PAGE->requires
->js('/question/qbank.js');
1748 echo '<div id="chooseqtypehead" class="hd">' . "\n";
1749 echo $OUTPUT->heading(get_string('chooseqtypetoadd', 'question'), 3);
1751 echo '<div id="chooseqtype">' . "\n";
1752 echo '<form action="' . $CFG->wwwroot
. '/question/question.php" method="get"><div id="qtypeformdiv">' . "\n";
1753 foreach ($hiddenparams as $name => $value) {
1754 echo '<input type="hidden" name="' . s($name) . '" value="' . s($value) . '" />' . "\n";
1757 echo '<div class="qtypes">' . "\n";
1758 echo '<div class="instruction">' . get_string('selectaqtypefordescription', 'question') . "</div>\n";
1759 echo '<div class="realqtypes">' . "\n";
1760 $fakeqtypes = array();
1761 foreach (question_bank
::get_creatable_qtypes() as $qtypename => $qtype) {
1762 if ($allowedqtypes && !in_array($qtypename, $allowedqtypes)) {
1765 if ($qtype->is_real_question_type()) {
1766 print_qtype_to_add_option($qtype);
1768 $fakeqtypes[] = $qtype;
1772 echo '<div class="fakeqtypes">' . "\n";
1773 foreach ($fakeqtypes as $qtype) {
1774 print_qtype_to_add_option($qtype);
1778 echo '<div class="submitbuttons">' . "\n";
1779 echo '<input type="submit" value="' . get_string('next') . '" id="chooseqtype_submit" />' . "\n";
1780 echo '<input type="submit" id="chooseqtypecancel" name="addcancel" value="' . get_string('cancel') . '" />' . "\n";
1781 echo "</div></form>\n";
1783 $PAGE->requires
->js_init_call('qtype_chooser.init', array('chooseqtype'));
1787 * Private function used by the preceding one.
1788 * @param question_type $qtype the question type.
1790 function print_qtype_to_add_option($qtype) {
1791 echo '<div class="qtypeoption">' . "\n";
1792 echo '<label for="' . $qtype->plugin_name() . '">';
1793 echo '<input type="radio" name="qtype" id="' . $qtype->plugin_name() .
1794 '" value="' . $qtype->name() . '" />';
1795 echo '<span class="qtypename">';
1796 $fakequestion = new stdClass();
1797 $fakequestion->qtype
= $qtype->name();
1798 echo print_question_icon($fakequestion);
1799 echo $qtype->menu_name() . '</span><span class="qtypesummary">' .
1800 get_string('pluginnamesummary', $qtype->plugin_name());
1801 echo "</span></label>\n";
1806 * Print a button for creating a new question. This will open question/addquestion.php,
1807 * which in turn goes to question/question.php before getting back to $params['returnurl']
1808 * (by default the question bank screen).
1810 * @param int $categoryid The id of the category that the new question should be added to.
1811 * @param array $params Other paramters to add to the URL. You need either $params['cmid'] or
1812 * $params['courseid'], and you should probably set $params['returnurl']
1813 * @param string $caption the text to display on the button.
1814 * @param string $tooltip a tooltip to add to the button (optional).
1815 * @param bool $disabled if true, the button will be disabled.
1817 function create_new_question_button($categoryid, $params, $caption, $tooltip = '', $disabled = false) {
1818 global $CFG, $PAGE, $OUTPUT;
1819 static $choiceformprinted = false;
1820 $params['category'] = $categoryid;
1821 $url = new moodle_url('/question/addquestion.php', $params);
1822 echo $OUTPUT->single_button($url, $caption, 'get', array('disabled'=>$disabled, 'title'=>$tooltip));
1824 $PAGE->requires
->yui2_lib('dragdrop');
1825 $PAGE->requires
->yui2_lib('container');
1826 if (!$choiceformprinted) {
1827 echo '<div id="qtypechoicecontainer">';
1828 print_choose_qtype_to_add_form(array());
1830 $choiceformprinted = true;