Merge branch 'MDL-26730' of git://github.com/timhunt/moodle
[moodle.git] / question / editlib.php
blobb07ad7551c03db9d84bf92b67ecd3adc86d55564
1 <?php
3 ///////////////////////////////////////////////////////////////////////////
4 // //
5 // NOTICE OF COPYRIGHT //
6 // //
7 // Moodle - Modular Object-Oriented Dynamic Learning Environment //
8 // http://moodle.org //
9 // //
10 // Copyright (C) 1999 onwards Martin Dougiamas and others //
11 // //
12 // This program is free software; you can redistribute it and/or modify //
13 // it under the terms of the GNU General Public License as published by //
14 // the Free Software Foundation; either version 2 of the License, or //
15 // (at your option) any later version. //
16 // //
17 // This program is distributed in the hope that it will be useful, //
18 // but WITHOUT ANY WARRANTY; without even the implied warranty of //
19 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //
20 // GNU General Public License for more details: //
21 // //
22 // http://www.gnu.org/copyleft/gpl.html //
23 // //
24 ///////////////////////////////////////////////////////////////////////////
26 /**
27 * Functions used to show question editing interface
29 * @license http://www.gnu.org/copyleft/gpl.html GNU Public License
30 * @package questionbank
31 *//** */
33 require_once($CFG->libdir.'/questionlib.php');
35 define('DEFAULT_QUESTIONS_PER_PAGE', 20);
37 function get_module_from_cmid($cmid) {
38 global $CFG, $DB;
39 if (!$cmrec = $DB->get_record_sql("SELECT cm.*, md.name as modname
40 FROM {course_modules} cm,
41 {modules} md
42 WHERE cm.id = ? AND
43 md.id = cm.module", array($cmid))){
44 print_error('invalidcoursemodule');
45 } elseif (!$modrec =$DB->get_record($cmrec->modname, array('id' => $cmrec->instance))) {
46 print_error('invalidcoursemodule');
48 $modrec->instance = $modrec->id;
49 $modrec->cmid = $cmrec->id;
50 $cmrec->name = $modrec->name;
52 return array($modrec, $cmrec);
54 /**
55 * Function to read all questions for category into big array
57 * @param int $category category number
58 * @param bool $noparent if true only questions with NO parent will be selected
59 * @param bool $recurse include subdirectories
60 * @param bool $export set true if this is called by questionbank export
61 * @author added by Howard Miller June 2004
63 function get_questions_category( $category, $noparent=false, $recurse=true, $export=true ) {
65 global $QTYPES, $DB;
67 // questions will be added to an array
68 $qresults = array();
70 // build sql bit for $noparent
71 $npsql = '';
72 if ($noparent) {
73 $npsql = " and parent='0' ";
76 // get (list) of categories
77 if ($recurse) {
78 $categorylist = question_categorylist($category->id);
80 else {
81 $categorylist = $category->id;
84 // get the list of questions for the category
85 list ($usql, $params) = $DB->get_in_or_equal(explode(',', $categorylist));
86 if ($questions = $DB->get_records_select("question","category $usql $npsql", $params, "qtype, name ASC")) {
88 // iterate through questions, getting stuff we need
89 foreach($questions as $question) {
90 $questiontype = $QTYPES[$question->qtype];
91 $question->export_process = $export;
92 $questiontype->get_question_options($question);
93 $qresults[] = $question;
97 return $qresults;
101 * @param integer $categoryid a category id.
102 * @return boolean whether this is the only top-level category in a context.
104 function question_is_only_toplevel_category_in_context($categoryid) {
105 global $DB;
106 return 1 == $DB->count_records_sql("
107 SELECT count(*)
108 FROM {question_categories} c1,
109 {question_categories} c2
110 WHERE c2.id = ?
111 AND c1.contextid = c2.contextid
112 AND c1.parent = 0 AND c2.parent = 0", array($categoryid));
116 * Check whether this user is allowed to delete this category.
118 * @param integer $todelete a category id.
120 function question_can_delete_cat($todelete) {
121 global $DB;
122 if (question_is_only_toplevel_category_in_context($todelete)) {
123 print_error('cannotdeletecate', 'question');
124 } else {
125 $contextid = $DB->get_field('question_categories', 'contextid', array('id' => $todelete));
126 require_capability('moodle/question:managecategory', get_context_instance_by_id($contextid));
130 abstract class question_bank_column_base {
132 * @var question_bank_view
134 protected $qbank;
137 * Constructor.
138 * @param $qbank the question_bank_view we are helping to render.
140 public function __construct(question_bank_view $qbank) {
141 $this->qbank = $qbank;
142 $this->init();
146 * A chance for subclasses to initialise themselves, for example to load lang strings,
147 * without having to override the constructor.
149 protected function init() {
152 public function is_extra_row() {
153 return false;
157 * Output the column header cell.
158 * @param integer $currentsort 0 for none. 1 for normal sort, -1 for reverse sort.
160 public function display_header() {
161 echo '<th class="header ' . $this->get_classes() . '" scope="col">';
162 $sortable = $this->is_sortable();
163 $name = $this->get_name();
164 $title = $this->get_title();
165 $tip = $this->get_title_tip();
166 if (is_array($sortable)) {
167 if ($title) {
168 echo '<div class="title">' . $title . '</div>';
170 $links = array();
171 foreach ($sortable as $subsort => $details) {
172 $links[] = $this->make_sort_link($name . '_' . $subsort,
173 $details['title'], '', !empty($details['reverse']));
175 echo '<div class="sorters">' . implode(' / ', $links) . '</div>';
176 } else if ($sortable) {
177 echo $this->make_sort_link($name, $title, $tip);
178 } else {
179 if ($tip) {
180 echo '<span title="' . $tip . '">';
182 echo $title;
183 if ($tip) {
184 echo '</span>';
187 echo "</th>\n";
191 * Title for this column. Not used if is_sortable returns an array.
192 * @param object $question the row from the $question table, augmented with extra information.
193 * @param string $rowclasses CSS class names that should be applied to this row of output.
195 abstract protected function get_title();
198 * @return string a fuller version of the name. Use this when get_title() returns
199 * something very short, and you want a longer version as a tool tip.
201 protected function get_title_tip() {
202 return '';
206 * Get a link that changes the sort order, and indicates the current sort state.
207 * @param $name internal name used for this type of sorting.
208 * @param $currentsort the current sort order -1, 0, 1 for descending, none, ascending.
209 * @param $title the link text.
210 * @param $defaultreverse whether the default sort order for this column is descending, rather than ascending.
211 * @return string HTML fragment.
213 protected function make_sort_link($sort, $title, $tip, $defaultreverse = false) {
214 $currentsort = $this->qbank->get_primary_sort_order($sort);
215 $newsortreverse = $defaultreverse;
216 if ($currentsort) {
217 $newsortreverse = $currentsort > 0;
219 if (!$tip) {
220 $tip = $title;
222 if ($newsortreverse) {
223 $tip = get_string('sortbyxreverse', '', $tip);
224 } else {
225 $tip = get_string('sortbyx', '', $tip);
227 $link = '<a href="' . $this->qbank->new_sort_url($sort, $newsortreverse) . '" title="' . $tip . '">';
228 $link .= $title;
229 if ($currentsort) {
230 $link .= $this->get_sort_icon($currentsort < 0);
232 $link .= '</a>';
233 return $link;
237 * Get an icon representing the corrent sort state.
238 * @param $reverse sort is descending, not ascending.
239 * @return string HTML image tag.
241 protected function get_sort_icon($reverse) {
242 global $OUTPUT;
243 if ($reverse) {
244 return ' <img src="' . $OUTPUT->pix_url('t/up') . '" alt="' . get_string('desc') . '" />';
245 } else {
246 return ' <img src="' . $OUTPUT->pix_url('t/down') . '" alt="' . get_string('asc') . '" />';
251 * Output this column.
252 * @param object $question the row from the $question table, augmented with extra information.
253 * @param string $rowclasses CSS class names that should be applied to this row of output.
255 public function display($question, $rowclasses) {
256 $this->display_start($question, $rowclasses);
257 $this->display_content($question, $rowclasses);
258 $this->display_end($question, $rowclasses);
261 protected function display_start($question, $rowclasses) {
262 echo '<td class="' . $this->get_classes() . '">';
266 * @return string the CSS classes to apply to every cell in this column.
268 protected function get_classes() {
269 $classes = $this->get_extra_classes();
270 $classes[] = $this->get_name();
271 return implode(' ', $classes);
275 * @param object $question the row from the $question table, augmented with extra information.
276 * @return string internal name for this column. Used as a CSS class name,
277 * and to store information about the current sort. Must match PARAM_ALPHA.
279 abstract public function get_name();
282 * @return array any extra class names you would like applied to every cell in this column.
284 public function get_extra_classes() {
285 return array();
289 * Output the contents of this column.
290 * @param object $question the row from the $question table, augmented with extra information.
291 * @param string $rowclasses CSS class names that should be applied to this row of output.
293 abstract protected function display_content($question, $rowclasses);
295 protected function display_end($question, $rowclasses) {
296 echo "</td>\n";
300 * Return an array 'table_alias' => 'JOIN clause' to bring in any data that
301 * this column required.
303 * The return values for all the columns will be checked. It is OK if two
304 * columns join in the same table with the same alias and identical JOIN clauses.
305 * If to columns try to use the same alias with different joins, you get an error.
306 * The only table included by default is the question table, which is aliased to 'q'.
308 * It is importnat that your join simply adds additional data (or NULLs) to the
309 * existing rows of the query. It must not cause additional rows.
311 * @return array 'table_alias' => 'JOIN clause'
313 public function get_extra_joins() {
314 return array();
318 * @return array fields required. use table alias 'q' for the question table, or one of the
319 * ones from get_extra_joins. Every field requested must specify a table prefix.
321 public function get_required_fields() {
322 return array();
326 * Can this column be sorted on? You can return either:
327 * + false for no (the default),
328 * + a field name, if sorting this column corresponds to sorting on that datbase field.
329 * + an array of subnames to sort on as follows
330 * return array(
331 * 'firstname' => array('field' => 'uc.firstname', 'title' => get_string('firstname')),
332 * 'lastname' => array('field' => 'uc.lastname', 'field' => get_string('lastname')),
333 * );
334 * As well as field, and field, you can also add 'revers' => 1 if you want the default sort
335 * order to be DESC.
336 * @return mixed as above.
338 public function is_sortable() {
339 return false;
343 * Helper method for building sort clauses.
344 * @param boolean $reverse whether the normal direction should be reversed.
345 * @param string $normaldir 'ASC' or 'DESC'
346 * @return string 'ASC' or 'DESC'
348 protected function sortorder($reverse) {
349 if ($reverse) {
350 return ' DESC';
351 } else {
352 return ' ASC';
357 * @param $reverse Whether to sort in the reverse of the default sort order.
358 * @param $subsort if is_sortable returns an array of subnames, then this will be
359 * one of those. Otherwise will be empty.
360 * @return string some SQL to go in the order by clause.
362 public function sort_expression($reverse, $subsort) {
363 $sortable = $this->is_sortable();
364 if (is_array($sortable)) {
365 if (array_key_exists($subsort, $sortable)) {
366 return $sortable[$subsort]['field'] . $this->sortorder($reverse, !empty($sortable[$subsort]['reverse']));
367 } else {
368 throw new coding_exception('Unexpected $subsort type: ' . $subsort);
370 } else if ($sortable) {
371 return $sortable . $this->sortorder($reverse);
372 } else {
373 throw new coding_exception('sort_expression called on a non-sortable column.');
379 * A column with a checkbox for each question with name q{questionid}.
381 class question_bank_checkbox_column extends question_bank_column_base {
382 protected $strselect;
383 protected $firstrow = true;
385 public function init() {
386 $this->strselect = get_string('select', 'quiz');
389 public function get_name() {
390 return 'checkbox';
393 protected function get_title() {
394 return '<input type="checkbox" disabled="disabled" id="qbheadercheckbox" />';
397 protected function get_title_tip() {
398 return get_string('selectquestionsforbulk', 'question');
401 protected function display_content($question, $rowclasses) {
402 global $PAGE;
403 echo '<input title="' . $this->strselect . '" type="checkbox" name="q' .
404 $question->id . '" id="checkq' . $question->id . '" value="1"/>';
405 if ($this->firstrow) {
406 $PAGE->requires->js_function_call('question_bank.init_checkbox_column', array(get_string('selectall'),
407 get_string('deselectall'), 'checkq' . $question->id));
408 $this->firstrow = false;
412 public function get_required_fields() {
413 return array('q.id');
418 * A column type for the name of the question type.
420 class question_bank_question_type_column extends question_bank_column_base {
421 public function get_name() {
422 return 'qtype';
425 protected function get_title() {
426 return get_string('qtypeveryshort', 'question');
429 protected function get_title_tip() {
430 return get_string('questiontype', 'question');
433 protected function display_content($question, $rowclasses) {
434 echo print_question_icon($question);
437 public function get_required_fields() {
438 return array('q.qtype');
441 public function is_sortable() {
442 return 'q.qtype';
447 * A column type for the name of the question name.
449 class question_bank_question_name_column extends question_bank_column_base {
450 protected $checkboxespresent = null;
452 public function get_name() {
453 return 'questionname';
456 protected function get_title() {
457 return get_string('question');
460 protected function label_for($question) {
461 if (is_null($this->checkboxespresent)) {
462 $this->checkboxespresent = $this->qbank->has_column('checkbox');
464 if ($this->checkboxespresent) {
465 return 'checkq' . $question->id;
466 } else {
467 return '';
471 protected function display_content($question, $rowclasses) {
472 $labelfor = $this->label_for($question);
473 if ($labelfor) {
474 echo '<label for="' . $labelfor . '">';
476 echo format_string($question->name);
477 if ($labelfor) {
478 echo '</label>';
482 public function get_required_fields() {
483 return array('q.id', 'q.name');
486 public function is_sortable() {
487 return 'q.name';
492 * A column type for the name of the question creator.
494 class question_bank_creator_name_column extends question_bank_column_base {
495 public function get_name() {
496 return 'creatorname';
499 protected function get_title() {
500 return get_string('createdby', 'question');
503 protected function display_content($question, $rowclasses) {
504 if (!empty($question->creatorfirstname) && !empty($question->creatorlastname)) {
505 $u = new stdClass;
506 $u->firstname = $question->creatorfirstname;
507 $u->lastname = $question->creatorlastname;
508 echo fullname($u);
512 public function get_extra_joins() {
513 return array('uc' => 'LEFT JOIN {user} uc ON uc.id = q.createdby');
516 public function get_required_fields() {
517 return array('uc.firstname AS creatorfirstname', 'uc.lastname AS creatorlastname');
520 public function is_sortable() {
521 return array(
522 'firstname' => array('field' => 'uc.firstname', 'title' => get_string('firstname')),
523 'lastname' => array('field' => 'uc.lastname', 'title' => get_string('lastname')),
529 * A column type for the name of the question last modifier.
531 class question_bank_modifier_name_column extends question_bank_column_base {
532 public function get_name() {
533 return 'modifiername';
536 protected function get_title() {
537 return get_string('lastmodifiedby', 'question');
540 protected function display_content($question, $rowclasses) {
541 if (!empty($question->modifierfirstname) && !empty($question->modifierlastname)) {
542 $u = new stdClass;
543 $u->firstname = $question->modifierfirstname;
544 $u->lastname = $question->modifierlastname;
545 echo fullname($u);
549 public function get_extra_joins() {
550 return array('um' => 'LEFT JOIN {user} um ON um.id = q.modifiedby');
553 public function get_required_fields() {
554 return array('um.firstname AS modifierfirstname', 'um.lastname AS modifierlastname');
557 public function is_sortable() {
558 return array(
559 'firstname' => array('field' => 'um.firstname', 'title' => get_string('firstname')),
560 'lastname' => array('field' => 'um.lastname', 'title' => get_string('lastname')),
566 * A base class for actions that are an icon that lets you manipulate the question in some way.
568 abstract class question_bank_action_column_base extends question_bank_column_base {
570 protected function get_title() {
571 return '&#160;';
574 public function get_extra_classes() {
575 return array('iconcol');
578 protected function print_icon($icon, $title, $url) {
579 global $OUTPUT;
580 echo '<a title="' . $title . '" href="' . $url . '">
581 <img src="' . $OUTPUT->pix_url($icon) . '" class="iconsmall" alt="' . $title . '" /></a>';
584 public function get_required_fields() {
585 return array('q.id');
589 class question_bank_edit_action_column extends question_bank_action_column_base {
590 protected $stredit;
591 protected $strview;
593 public function init() {
594 parent::init();
595 $this->stredit = get_string('edit');
596 $this->strview = get_string('view');
599 public function get_name() {
600 return 'editaction';
603 protected function display_content($question, $rowclasses) {
604 if (question_has_capability_on($question, 'edit') ||
605 question_has_capability_on($question, 'move')) {
606 $this->print_icon('t/edit', $this->stredit, $this->qbank->edit_question_url($question->id));
607 } else {
608 $this->print_icon('i/info', $this->strview, $this->qbank->edit_question_url($question->id));
613 class question_bank_preview_action_column extends question_bank_action_column_base {
614 protected $strpreview;
616 public function init() {
617 parent::init();
618 $this->strpreview = get_string('preview');
621 public function get_name() {
622 return 'previewaction';
625 protected function display_content($question, $rowclasses) {
626 global $OUTPUT;
627 if (question_has_capability_on($question, 'use')) {
628 // Build the icon.
629 $image = $OUTPUT->pix_icon('t/preview', $this->strpreview);
631 $link = new moodle_url($this->qbank->preview_question_url($question->id));
632 parse_str(QUESTION_PREVIEW_POPUP_OPTIONS, $options);
633 $action = new popup_action('click', $link, 'questionpreview', $options);
635 echo $OUTPUT->action_link($link, $image, $action, array('title' => $this->strpreview));
639 public function get_required_fields() {
640 return array('q.id');
644 class question_bank_move_action_column extends question_bank_action_column_base {
645 protected $strmove;
647 public function init() {
648 parent::init();
649 $this->strmove = get_string('move');
652 public function get_name() {
653 return 'moveaction';
656 protected function display_content($question, $rowclasses) {
657 if (question_has_capability_on($question, 'move')) {
658 $this->print_icon('t/move', $this->strmove, $this->qbank->move_question_url($question->id));
664 * action to delete (or hide) a question, or restore a previously hidden question.
666 class question_bank_delete_action_column extends question_bank_action_column_base {
667 protected $strdelete;
668 protected $strrestore;
670 public function init() {
671 parent::init();
672 $this->strdelete = get_string('delete');
673 $this->strrestore = get_string('restore');
676 public function get_name() {
677 return 'deleteaction';
680 protected function display_content($question, $rowclasses) {
681 if (question_has_capability_on($question, 'edit')) {
682 if ($question->hidden) {
683 $url = new moodle_url($this->qbank->base_url(), array('unhide' => $question->id, 'sesskey'=>sesskey()));
684 $this->print_icon('t/restore', $this->strrestore, $url);
685 } else {
686 $url = new moodle_url($this->qbank->base_url(), array('deleteselected' => $question->id, 'q' . $question->id => 1, 'sesskey'=>sesskey()));
687 $this->print_icon('t/delete', $this->strdelete, $url);
692 public function get_required_fields() {
693 return array('q.id', 'q.hidden');
698 * Base class for 'columns' that are actually displayed as a row following the main question row.
700 abstract class question_bank_row_base extends question_bank_column_base {
701 public function is_extra_row() {
702 return true;
705 protected function display_start($question, $rowclasses) {
706 if ($rowclasses) {
707 echo '<tr class="' . $rowclasses . '">' . "\n";
708 } else {
709 echo "<tr>\n";
711 echo '<td colspan="' . $this->qbank->get_column_count() . '" class="' . $this->get_name() . '">';
714 protected function display_end($question, $rowclasses) {
715 echo "</td></tr>\n";
720 * A column type for the name of the question name.
722 class question_bank_question_text_row extends question_bank_row_base {
723 protected $formatoptions;
725 protected function init() {
726 $this->formatoptions = new stdClass;
727 $this->formatoptions->noclean = true;
728 $this->formatoptions->para = false;
731 public function get_name() {
732 return 'questiontext';
735 protected function get_title() {
736 return get_string('questiontext', 'question');
739 protected function display_content($question, $rowclasses) {
740 $text = format_text($question->questiontext, $question->questiontextformat,
741 $this->formatoptions, $this->qbank->get_courseid());
742 if ($text == '') {
743 $text = '&#160;';
745 echo $text;
748 public function get_required_fields() {
749 return array('q.questiontext', 'q.questiontextformat');
754 * This class prints a view of the question bank, including
755 * + Some controls to allow users to to select what is displayed.
756 * + A list of questions as a table.
757 * + Further controls to do things with the questions.
759 * This class gives a basic view, and provides plenty of hooks where subclasses
760 * can override parts of the display.
762 * The list of questions presented as a table is generated by creating a list of
763 * question_bank_column objects, one for each 'column' to be displayed. These
764 * manage
765 * + outputting the contents of that column, given a $question object, but also
766 * + generating the right fragments of SQL to ensure the necessary data is present,
767 * and sorted in the right order.
768 * + outputting table headers.
770 class question_bank_view {
771 const MAX_SORTS = 3;
773 protected $baseurl;
774 protected $editquestionurl;
775 protected $quizorcourseid;
776 protected $contexts;
777 protected $cm;
778 protected $course;
779 protected $knowncolumntypes;
780 protected $visiblecolumns;
781 protected $extrarows;
782 protected $requiredcolumns;
783 protected $sort;
784 protected $lastchangedid;
785 protected $countsql;
786 protected $loadsql;
787 protected $sqlparams;
789 public function __construct($contexts, $pageurl, $course, $cm = null) {
790 global $CFG, $PAGE;
792 $this->contexts = $contexts;
793 $this->baseurl = $pageurl;
794 $this->course = $course;
795 $this->cm = $cm;
797 if (!empty($cm) && $cm->modname == 'quiz') {
798 $this->quizorcourseid = '&amp;quizid=' . $cm->instance;
799 } else {
800 $this->quizorcourseid = '&amp;courseid=' .$this->course->id;
803 // Create the url of the new question page to forward to.
804 $returnurl = str_replace($CFG->wwwroot, '', $pageurl->out(false));
805 $this->editquestionurl = new moodle_url('/question/question.php',
806 array('returnurl' => $returnurl));
807 if ($cm !== null){
808 $this->editquestionurl->param('cmid', $cm->id);
809 } else {
810 $this->editquestionurl->param('courseid', $this->course->id);
813 $this->lastchangedid = optional_param('lastchanged',0,PARAM_INT);
815 $this->init_column_types();
816 $this->init_columns($this->wanted_columns());
817 $this->init_sort();
819 $PAGE->requires->yui2_lib('container');
822 protected function wanted_columns() {
823 $columns = array('checkbox', 'qtype', 'questionname', 'editaction',
824 'previewaction', 'moveaction', 'deleteaction', 'creatorname',
825 'modifiername');
826 if (optional_param('qbshowtext', false, PARAM_BOOL)) {
827 $columns[] = 'questiontext';
829 return $columns;
832 protected function known_field_types() {
833 return array(
834 new question_bank_checkbox_column($this),
835 new question_bank_question_type_column($this),
836 new question_bank_question_name_column($this),
837 new question_bank_creator_name_column($this),
838 new question_bank_modifier_name_column($this),
839 new question_bank_edit_action_column($this),
840 new question_bank_preview_action_column($this),
841 new question_bank_move_action_column($this),
842 new question_bank_delete_action_column($this),
843 new question_bank_question_text_row($this),
847 protected function init_column_types() {
848 $this->knowncolumntypes = array();
849 foreach ($this->known_field_types() as $col) {
850 $this->knowncolumntypes[$col->get_name()] = $col;
854 protected function init_columns($wanted) {
855 $this->visiblecolumns = array();
856 $this->extrarows = array();
857 foreach ($wanted as $colname) {
858 if (!isset($this->knowncolumntypes[$colname])) {
859 throw new coding_exception('Unknown column type ' . $colname . ' requested in init columns.');
861 $column = $this->knowncolumntypes[$colname];
862 if ($column->is_extra_row()) {
863 $this->extrarows[$colname] = $column;
864 } else {
865 $this->visiblecolumns[$colname] = $column;
868 $this->requiredcolumns = array_merge($this->visiblecolumns, $this->extrarows);
872 * @param string $colname a column internal name.
873 * @return boolean is this column included in the output?
875 public function has_column($colname) {
876 return isset($this->visiblecolumns[$colname]);
880 * @return integer The number of columns in the table.
882 public function get_column_count() {
883 return count($this->visiblecolumns);
886 public function get_courseid() {
887 return $this->course->id;
890 protected function init_sort() {
891 $this->init_sort_from_params();
892 if (empty($this->sort)) {
893 $this->sort = $this->default_sort();
898 * Deal with a sort name of the forum columnname, or colname_subsort by
899 * breaking it up, validating the bits that are presend, and returning them.
900 * If there is no subsort, then $subsort is returned as ''.
901 * @return array array($colname, $subsort).
903 protected function parse_subsort($sort) {
904 /// Do the parsing.
905 if (strpos($sort, '_') !== false) {
906 list($colname, $subsort) = explode('_', $sort, 2);
907 } else {
908 $colname = $sort;
909 $subsort = '';
911 /// Validate the column name.
912 if (!isset($this->knowncolumntypes[$colname]) || !$this->knowncolumntypes[$colname]->is_sortable()) {
913 for ($i = 1; $i <= question_bank_view::MAX_SORTS; $i++) {
914 $this->baseurl->remove_params('qbs' . $i);
916 throw new moodle_exception('unknownsortcolumn', '', $link = $this->baseurl->out(), $colname);
918 /// Validate the subsort, if present.
919 if ($subsort) {
920 $subsorts = $this->knowncolumntypes[$colname]->is_sortable();
921 if (!is_array($subsorts) || !isset($subsorts[$subsort])) {
922 throw new moodle_exception('unknownsortcolumn', '', $link = $this->baseurl->out(), $sort);
925 return array($colname, $subsort);
928 protected function init_sort_from_params() {
929 $this->sort = array();
930 for ($i = 1; $i <= question_bank_view::MAX_SORTS; $i++) {
931 if (!$sort = optional_param('qbs' . $i, '', PARAM_ALPHAEXT)) {
932 break;
934 // Work out the appropriate order.
935 $order = 1;
936 if ($sort[0] == '-') {
937 $order = -1;
938 $sort = substr($sort, 1);
939 if (!$sort) {
940 break;
943 // Deal with subsorts.
944 list($colname, $subsort) = $this->parse_subsort($sort);
945 $this->requiredcolumns[$colname] = $this->knowncolumntypes[$colname];
946 $this->sort[$sort] = $order;
950 protected function sort_to_params($sorts) {
951 $params = array();
952 $i = 0;
953 foreach ($sorts as $sort => $order) {
954 $i += 1;
955 if ($order < 0) {
956 $sort = '-' . $sort;
958 $params['qbs' . $i] = $sort;
960 return $params;
963 protected function default_sort() {
964 return array('qtype' => 1, 'questionname' => 1);
968 * @param $sort a column or column_subsort name.
969 * @return integer the current sort order for this column -1, 0, 1
971 public function get_primary_sort_order($sort) {
972 $order = reset($this->sort);
973 $primarysort = key($this->sort);
974 if ($sort == $primarysort) {
975 return $order;
976 } else {
977 return 0;
982 * Get a URL to redisplay the page with a new sort for the question bank.
983 * @param string $sort the column, or column_subsort to sort on.
984 * @param boolean $newsortreverse whether to sort in reverse order.
985 * @return string The new URL.
987 public function new_sort_url($sort, $newsortreverse) {
988 if ($newsortreverse) {
989 $order = -1;
990 } else {
991 $order = 1;
993 // Tricky code to add the new sort at the start, removing it from where it was before, if it was present.
994 $newsort = array_reverse($this->sort);
995 if (isset($newsort[$sort])) {
996 unset($newsort[$sort]);
998 $newsort[$sort] = $order;
999 $newsort = array_reverse($newsort);
1000 if (count($newsort) > question_bank_view::MAX_SORTS) {
1001 $newsort = array_slice($newsort, 0, question_bank_view::MAX_SORTS, true);
1003 return $this->baseurl->out(true, $this->sort_to_params($newsort));
1006 protected function build_query_sql($category, $recurse, $showhidden) {
1007 global $DB;
1009 /// Get the required tables.
1010 $joins = array();
1011 foreach ($this->requiredcolumns as $column) {
1012 $extrajoins = $column->get_extra_joins();
1013 foreach ($extrajoins as $prefix => $join) {
1014 if (isset($joins[$prefix]) && $joins[$prefix] != $join) {
1015 throw new coding_exception('Join ' . $join . ' conflicts with previous join ' . $joins[$prefix]);
1017 $joins[$prefix] = $join;
1021 /// Get the required fields.
1022 $fields = array('q.hidden', 'q.category');
1023 foreach ($this->visiblecolumns as $column) {
1024 $fields = array_merge($fields, $column->get_required_fields());
1026 foreach ($this->extrarows as $row) {
1027 $fields = array_merge($fields, $row->get_required_fields());
1029 $fields = array_unique($fields);
1031 /// Build the order by clause.
1032 $sorts = array();
1033 foreach ($this->sort as $sort => $order) {
1034 list($colname, $subsort) = $this->parse_subsort($sort);
1035 $sorts[] = $this->knowncolumntypes[$colname]->sort_expression($order < 0, $subsort);
1038 /// Build the where clause.
1039 $tests = array('parent = 0');
1041 if (!$showhidden) {
1042 $tests[] = 'hidden = 0';
1045 if ($recurse) {
1046 $categoryids = explode(',', question_categorylist($category->id));
1047 } else {
1048 $categoryids = array($category->id);
1050 list($catidtest, $params) = $DB->get_in_or_equal($categoryids, SQL_PARAMS_NAMED, 'cat0000');
1051 $tests[] = 'q.category ' . $catidtest;
1052 $this->sqlparams = $params;
1054 /// Build the SQL.
1055 $sql = ' FROM {question} q ' . implode(' ', $joins);
1056 $sql .= ' WHERE ' . implode(' AND ', $tests);
1057 $this->countsql = 'SELECT count(1)' . $sql;
1058 $this->loadsql = 'SELECT ' . implode(', ', $fields) . $sql . ' ORDER BY ' . implode(', ', $sorts);
1059 $this->sqlparams = $params;
1062 protected function get_question_count() {
1063 global $DB;
1064 return $DB->count_records_sql($this->countsql, $this->sqlparams);
1067 protected function load_page_questions($page, $perpage) {
1068 global $DB;
1069 $questions = $DB->get_recordset_sql($this->loadsql, $this->sqlparams, $page*$perpage, $perpage);
1070 if (!$questions->valid()) {
1071 /// No questions on this page. Reset to page 0.
1072 $questions = $DB->get_recordset_sql($this->loadsql, $this->sqlparams, 0, $perpage);
1074 return $questions;
1077 public function base_url() {
1078 return $this->baseurl;
1081 public function edit_question_url($questionid) {
1082 return $this->editquestionurl->out(true, array('id' => $questionid));
1085 public function move_question_url($questionid) {
1086 return $this->editquestionurl->out(true, array('id' => $questionid, 'movecontext' => 1));
1089 public function preview_question_url($questionid) {
1090 global $CFG;
1091 return $CFG->wwwroot . '/question/preview.php?id=' . $questionid . '&amp;courseid=' . $this->course->id;
1095 * Shows the question bank editing interface.
1097 * The function also processes a number of actions:
1099 * Actions affecting the question pool:
1100 * move Moves a question to a different category
1101 * deleteselected Deletes the selected questions from the category
1102 * Other actions:
1103 * category Chooses the category
1104 * displayoptions Sets display options
1106 public function display($tabname, $page, $perpage, $sortorder,
1107 $sortorderdecoded, $cat, $recurse, $showhidden, $showquestiontext){
1108 global $PAGE, $OUTPUT;
1110 if ($this->process_actions_needing_ui()) {
1111 return;
1114 $PAGE->requires->js('/question/qbank.js');
1116 // Category selection form
1117 echo $OUTPUT->heading(get_string('questionbank', 'question'), 2);
1119 $this->display_category_form($this->contexts->having_one_edit_tab_cap($tabname),
1120 $this->baseurl, $cat);
1121 $this->display_options($recurse, $showhidden, $showquestiontext);
1123 if (!$category = $this->get_current_category($cat)) {
1124 return;
1126 $this->print_category_info($category);
1128 // continues with list of questions
1129 $this->display_question_list($this->contexts->having_one_edit_tab_cap($tabname), $this->baseurl, $cat, $this->cm,
1130 $recurse, $page, $perpage, $showhidden, $sortorder, $sortorderdecoded, $showquestiontext,
1131 $this->contexts->having_cap('moodle/question:add'));
1134 protected function print_choose_category_message($categoryandcontext) {
1135 echo "<p style=\"text-align:center;\"><b>";
1136 print_string("selectcategoryabove", "quiz");
1137 echo "</b></p>";
1140 protected function get_current_category($categoryandcontext) {
1141 global $DB, $OUTPUT;
1142 list($categoryid, $contextid) = explode(',', $categoryandcontext);
1143 if (!$categoryid) {
1144 $this->print_choose_category_message($categoryandcontext);
1145 return false;
1148 if (!$category = $DB->get_record('question_categories',
1149 array('id' => $categoryid, 'contextid' => $contextid))) {
1150 echo $OUTPUT->box_start('generalbox questionbank');
1151 echo $OUTPUT->notification('Category not found!');
1152 echo $OUTPUT->box_end();
1153 return false;
1156 return $category;
1159 protected function print_category_info($category) {
1160 $formatoptions = new stdClass;
1161 $formatoptions->noclean = true;
1162 $formatoptions->overflowdiv = true;
1163 echo '<div class="boxaligncenter">';
1164 echo format_text($category->info, FORMAT_MOODLE, $formatoptions, $this->course->id);
1165 echo "</div>\n";
1169 * prints a form to choose categories
1171 protected function display_category_form($contexts, $pageurl, $current) {
1172 global $CFG, $OUTPUT;
1174 /// Get all the existing categories now
1175 echo '<div class="choosecategory">';
1176 $catmenu = question_category_options($contexts, false, 0, true);
1178 $select = new single_select($this->baseurl, 'category', $catmenu, $current, null, 'catmenu');
1179 $select->set_label(get_string('selectacategory', 'question'));
1180 echo $OUTPUT->render($select);
1181 echo "</div>\n";
1184 protected function display_options($recurse = 1, $showhidden = false, $showquestiontext = false) {
1185 echo '<form method="get" action="edit.php" id="displayoptions">';
1186 echo "<fieldset class='invisiblefieldset'>";
1187 echo html_writer::input_hidden_params($this->baseurl, array('recurse', 'showhidden', 'showquestiontext'));
1188 $this->display_category_form_checkbox('recurse', get_string('recurse', 'quiz'));
1189 $this->display_category_form_checkbox('showhidden', get_string('showhidden', 'quiz'));
1190 $this->display_category_form_checkbox('qbshowtext', get_string('showquestiontext', 'quiz'));
1191 echo '<noscript><div class="centerpara"><input type="submit" value="'. get_string('go') .'" />';
1192 echo '</div></noscript></fieldset></form>';
1196 * Print a single option checkbox. Used by the preceeding.
1198 protected function display_category_form_checkbox($name, $label) {
1199 echo '<div><input type="hidden" id="' . $name . '_off" name="' . $name . '" value="0" />';
1200 echo '<input type="checkbox" id="' . $name . '_on" name="' . $name . '" value="1"';
1201 if (optional_param($name, false, PARAM_BOOL)) {
1202 echo ' checked="checked"';
1204 echo ' onchange="getElementById(\'displayoptions\').submit(); return true;" />';
1205 echo '<label for="' . $name . '_on">' . $label . '</label>';
1206 echo "</div>\n";
1209 protected function create_new_question_form($category, $canadd) {
1210 global $CFG;
1211 echo '<div class="createnewquestion">';
1212 if ($canadd) {
1213 create_new_question_button($category->id, $this->editquestionurl->params(),
1214 get_string('createnewquestion', 'question'));
1215 } else {
1216 print_string('nopermissionadd', 'question');
1218 echo '</div>';
1222 * Prints the table of questions in a category with interactions
1224 * @param object $course The course object
1225 * @param int $categoryid The id of the question category to be displayed
1226 * @param int $cm The course module record if we are in the context of a particular module, 0 otherwise
1227 * @param int $recurse This is 1 if subcategories should be included, 0 otherwise
1228 * @param int $page The number of the page to be displayed
1229 * @param int $perpage Number of questions to show per page
1230 * @param boolean $showhidden True if also hidden questions should be displayed
1231 * @param boolean $showquestiontext whether the text of each question should be shown in the list
1233 protected function display_question_list($contexts, $pageurl, $categoryandcontext,
1234 $cm = null, $recurse=1, $page=0, $perpage=100, $showhidden=false,
1235 $sortorder='typename', $sortorderdecoded='qtype, name ASC',
1236 $showquestiontext = false, $addcontexts = array()) {
1237 global $CFG, $DB, $OUTPUT;
1239 $category = $this->get_current_category($categoryandcontext);
1241 $cmoptions = new stdClass;
1242 $cmoptions->hasattempts = !empty($this->quizhasattempts);
1244 $strselectall = get_string("selectall", "quiz");
1245 $strselectnone = get_string("selectnone", "quiz");
1246 $strdelete = get_string("delete");
1248 list($categoryid, $contextid) = explode(',', $categoryandcontext);
1249 $catcontext = get_context_instance_by_id($contextid);
1251 $canadd = has_capability('moodle/question:add', $catcontext);
1252 $caneditall =has_capability('moodle/question:editall', $catcontext);
1253 $canuseall =has_capability('moodle/question:useall', $catcontext);
1254 $canmoveall =has_capability('moodle/question:moveall', $catcontext);
1256 $this->create_new_question_form($category, $canadd);
1258 $this->build_query_sql($category, $recurse, $showhidden);
1259 $totalnumber = $this->get_question_count();
1260 if ($totalnumber == 0) {
1261 return;
1264 $questions = $this->load_page_questions($page, $perpage);
1266 echo '<div class="categorypagingbarcontainer">';
1267 $pageing_url = new moodle_url('edit.php');
1268 $r = $pageing_url->params($pageurl->params());
1269 $pagingbar = new paging_bar($totalnumber, $page, $perpage, $pageing_url);
1270 $pagingbar->pagevar = 'qpage';
1271 echo $OUTPUT->render($pagingbar);
1272 echo '</div>';
1274 echo '<form method="post" action="edit.php">';
1275 echo '<fieldset class="invisiblefieldset" style="display: block;">';
1276 echo '<input type="hidden" name="sesskey" value="'.sesskey().'" />';
1277 echo html_writer::input_hidden_params($pageurl);
1279 echo '<div class="categoryquestionscontainer">';
1280 $this->start_table();
1281 $rowcount = 0;
1282 foreach ($questions as $question) {
1283 $this->print_table_row($question, $rowcount);
1284 $rowcount += 1;
1286 $this->end_table();
1287 echo "</div>\n";
1289 echo '<div class="categorypagingbarcontainer pagingbottom">';
1290 echo $OUTPUT->render($pagingbar);
1291 if ($totalnumber > DEFAULT_QUESTIONS_PER_PAGE) {
1292 if ($perpage == DEFAULT_QUESTIONS_PER_PAGE) {
1293 $url = new moodle_url('edit.php', ($pageurl->params()+array('qperpage'=>1000)));
1294 $showall = '<a href="'.$url.'">'.get_string('showall', 'moodle', $totalnumber).'</a>';
1295 } else {
1296 $url = new moodle_url('edit.php', ($pageurl->params()+array('qperpage'=>DEFAULT_QUESTIONS_PER_PAGE)));
1297 $showall = '<a href="'.$url.'">'.get_string('showperpage', 'moodle', DEFAULT_QUESTIONS_PER_PAGE).'</a>';
1299 echo "<div class='paging'>$showall</div>";
1301 echo '</div>';
1303 echo '<div class="modulespecificbuttonscontainer">';
1304 if ($caneditall || $canmoveall || $canuseall){
1305 echo '<strong>&nbsp;'.get_string('withselected', 'quiz').':</strong><br />';
1307 if (function_exists('module_specific_buttons')) {
1308 echo module_specific_buttons($this->cm->id,$cmoptions);
1311 // print delete and move selected question
1312 if ($caneditall) {
1313 echo '<input type="submit" name="deleteselected" value="' . $strdelete . "\" />\n";
1316 if ($canmoveall && count($addcontexts)) {
1317 echo '<input type="submit" name="move" value="'.get_string('moveto', 'quiz')."\" />\n";
1318 question_category_select_menu($addcontexts, false, 0, "$category->id,$category->contextid");
1321 if (function_exists('module_specific_controls') && $canuseall) {
1322 $modulespecific = module_specific_controls($totalnumber, $recurse, $category, $this->cm->id,$cmoptions);
1323 if(!empty($modulespecific)){
1324 echo "<hr />$modulespecific";
1328 echo "</div>\n";
1330 echo '</fieldset>';
1331 echo "</form>\n";
1334 protected function start_table() {
1335 echo '<table id="categoryquestions">' . "\n";
1336 echo "<thead>\n";
1337 $this->print_table_headers();
1338 echo "</thead>\n";
1339 echo "<tbody>\n";
1342 protected function end_table() {
1343 echo "</tbody>\n";
1344 echo "</table>\n";
1347 protected function print_table_headers() {
1348 echo "<tr>\n";
1349 foreach ($this->visiblecolumns as $column) {
1350 $column->display_header();
1352 echo "</tr>\n";
1355 protected function get_row_classes($question, $rowcount) {
1356 $classes = array();
1357 if ($question->hidden) {
1358 $classes[] = 'dimmed_text';
1360 if ($question->id == $this->lastchangedid) {
1361 $classes[] ='highlight';
1363 if (!empty($this->extrarows)) {
1364 $classes[] = 'r' . ($rowcount % 2);
1366 return $classes;
1369 protected function print_table_row($question, $rowcount) {
1370 $rowclasses = implode(' ', $this->get_row_classes($question, $rowcount));
1371 if ($rowclasses) {
1372 echo '<tr class="' . $rowclasses . '">' . "\n";
1373 } else {
1374 echo "<tr>\n";
1376 foreach ($this->visiblecolumns as $column) {
1377 $column->display($question, $rowclasses);
1379 echo "</tr>\n";
1380 foreach ($this->extrarows as $row) {
1381 $row->display($question, $rowclasses);
1385 public function process_actions() {
1386 global $CFG, $DB;
1387 /// Now, check for commands on this page and modify variables as necessary
1388 if (optional_param('move', false, PARAM_BOOL) and confirm_sesskey()) {
1389 // Move selected questions to new category
1390 $category = required_param('category', PARAM_SEQUENCE);
1391 list($tocategoryid, $contextid) = explode(',', $category);
1392 if (! $tocategory = $DB->get_record('question_categories', array('id' => $tocategoryid, 'contextid' => $contextid))) {
1393 print_error('cannotfindcate', 'question');
1395 $tocontext = get_context_instance_by_id($contextid);
1396 require_capability('moodle/question:add', $tocontext);
1397 $rawdata = (array) data_submitted();
1398 $questionids = array();
1399 foreach ($rawdata as $key => $value) { // Parse input for question ids
1400 if (preg_match('!^q([0-9]+)$!', $key, $matches)) {
1401 $key = $matches[1];
1402 $questionids[] = $key;
1405 if ($questionids) {
1406 list($usql, $params) = $DB->get_in_or_equal($questionids);
1407 $sql = "";
1408 $questions = $DB->get_records_sql("
1409 SELECT q.*, c.contextid
1410 FROM {question} q
1411 JOIN {question_categories} c ON c.id = q.category
1412 WHERE q.id $usql", $params);
1413 foreach ($questions as $question){
1414 question_require_capability_on($question, 'move');
1416 question_move_questions_to_category($questionids, $tocategory->id);
1417 redirect($this->baseurl->out(false,
1418 array('category' => "$tocategoryid,$contextid")));
1422 if (optional_param('deleteselected', false, PARAM_BOOL)) { // delete selected questions from the category
1423 if (($confirm = optional_param('confirm', '', PARAM_ALPHANUM)) and confirm_sesskey()) { // teacher has already confirmed the action
1424 $deleteselected = required_param('deleteselected', PARAM_RAW);
1425 if ($confirm == md5($deleteselected)) {
1426 if ($questionlist = explode(',', $deleteselected)) {
1427 // for each question either hide it if it is in use or delete it
1428 foreach ($questionlist as $questionid) {
1429 $questionid = (int)$questionid;
1430 question_require_capability_on($questionid, 'edit');
1431 if ($DB->record_exists('quiz_question_instances', array('question' => $questionid))) {
1432 $DB->set_field('question', 'hidden', 1, array('id' => $questionid));
1433 } else {
1434 delete_question($questionid);
1438 redirect($this->baseurl);
1439 } else {
1440 print_error('invalidconfirm', 'question');
1445 // Unhide a question
1446 if(($unhide = optional_param('unhide', '', PARAM_INT)) and confirm_sesskey()) {
1447 question_require_capability_on($unhide, 'edit');
1448 $DB->set_field('question', 'hidden', 0, array('id' => $unhide));
1449 redirect($this->baseurl);
1453 public function process_actions_needing_ui() {
1454 global $DB, $OUTPUT;
1455 if (optional_param('deleteselected', false, PARAM_BOOL)) {
1456 // make a list of all the questions that are selected
1457 $rawquestions = $_REQUEST; // This code is called by both POST forms and GET links, so cannot use data_submitted.
1458 $questionlist = ''; // comma separated list of ids of questions to be deleted
1459 $questionnames = ''; // string with names of questions separated by <br /> with
1460 // an asterix in front of those that are in use
1461 $inuse = false; // set to true if at least one of the questions is in use
1462 foreach ($rawquestions as $key => $value) { // Parse input for question ids
1463 if (preg_match('!^q([0-9]+)$!', $key, $matches)) {
1464 $key = $matches[1];
1465 $questionlist .= $key.',';
1466 question_require_capability_on($key, 'edit');
1467 if ($DB->record_exists('quiz_question_instances', array('question' => $key))) {
1468 $questionnames .= '* ';
1469 $inuse = true;
1471 $questionnames .= $DB->get_field('question', 'name', array('id' => $key)) . '<br />';
1474 if (!$questionlist) { // no questions were selected
1475 redirect($this->baseurl);
1477 $questionlist = rtrim($questionlist, ',');
1479 // Add an explanation about questions in use
1480 if ($inuse) {
1481 $questionnames .= '<br />'.get_string('questionsinuse', 'quiz');
1483 $baseurl = new moodle_url('edit.php', $this->baseurl->params());
1484 $deleteurl = new moodle_url($baseurl, array('deleteselected'=>$questionlist, 'confirm'=>md5($questionlist), 'sesskey'=>sesskey()));
1486 echo $OUTPUT->confirm(get_string("deletequestionscheck", "quiz", $questionnames), $deleteurl, $baseurl);
1488 return true;
1494 * Common setup for all pages for editing questions.
1495 * @param string $baseurl the name of the script calling this funciton. For examle 'qusetion/edit.php'.
1496 * @param string $edittab code for this edit tab
1497 * @param boolean $requirecmid require cmid? default false
1498 * @param boolean $requirecourseid require courseid, if cmid is not given? default true
1499 * @return array $thispageurl, $contexts, $cmid, $cm, $module, $pagevars
1501 function question_edit_setup($edittab, $baseurl, $requirecmid = false, $requirecourseid = true) {
1502 global $DB, $PAGE;
1504 //$thispageurl is used to construct urls for all question edit pages we link to from this page. It contains an array
1505 //of parameters that are passed from page to page.
1506 // $thispageurl = new moodle_url($PAGE->url); //TODO: this looks dumb, because this method is called BEFORE $PAGE->set_page() !!!!
1507 $thispageurl = new moodle_url($baseurl);
1508 $thispageurl->remove_all_params(); // We are going to explicity add back everything important - this avoids unwanted params from being retained.
1510 if ($requirecmid){
1511 $cmid =required_param('cmid', PARAM_INT);
1512 } else {
1513 $cmid = optional_param('cmid', 0, PARAM_INT);
1515 if ($cmid){
1516 list($module, $cm) = get_module_from_cmid($cmid);
1517 $courseid = $cm->course;
1518 $thispageurl->params(compact('cmid'));
1519 require_login($courseid, false, $cm);
1520 $thiscontext = get_context_instance(CONTEXT_MODULE, $cmid);
1521 } else {
1522 $module = null;
1523 $cm = null;
1524 if ($requirecourseid){
1525 $courseid = required_param('courseid', PARAM_INT);
1526 } else {
1527 $courseid = optional_param('courseid', 0, PARAM_INT);
1529 if ($courseid){
1530 $thispageurl->params(compact('courseid'));
1531 require_login($courseid, false);
1532 $thiscontext = get_context_instance(CONTEXT_COURSE, $courseid);
1533 } else {
1534 $thiscontext = null;
1537 if (strpos($baseurl, '/question/') === 0) {
1538 navigation_node::override_active_url($thispageurl);
1541 if ($thiscontext){
1542 $contexts = new question_edit_contexts($thiscontext);
1543 $contexts->require_one_edit_tab_cap($edittab);
1545 } else {
1546 $contexts = null;
1551 $pagevars['qpage'] = optional_param('qpage', -1, PARAM_INT);
1553 //pass 'cat' from page to page and when 'category' comes from a drop down menu
1554 //then we also reset the qpage so we go to page 1 of
1555 //a new cat.
1556 $pagevars['cat'] = optional_param('cat', 0, PARAM_SEQUENCE);// if empty will be set up later
1557 if ($category = optional_param('category', 0, PARAM_SEQUENCE)){
1558 if ($pagevars['cat'] != $category){ // is this a move to a new category?
1559 $pagevars['cat'] = $category;
1560 $pagevars['qpage'] = 0;
1563 if ($pagevars['cat']){
1564 $thispageurl->param('cat', $pagevars['cat']);
1566 if ($pagevars['qpage'] > -1) {
1567 $thispageurl->param('qpage', $pagevars['qpage']);
1568 } else {
1569 $pagevars['qpage'] = 0;
1572 $pagevars['qperpage'] = optional_param('qperpage', -1, PARAM_INT);
1573 if ($pagevars['qperpage'] > -1) {
1574 $thispageurl->param('qperpage', $pagevars['qperpage']);
1575 } else {
1576 $pagevars['qperpage'] = DEFAULT_QUESTIONS_PER_PAGE;
1579 $sortoptions = array('alpha' => 'name, qtype ASC',
1580 'typealpha' => 'qtype, name ASC',
1581 'age' => 'id ASC');
1583 if ($sortorder = optional_param('qsortorder', '', PARAM_ALPHA)) {
1584 $pagevars['qsortorderdecoded'] = $sortoptions[$sortorder];
1585 $pagevars['qsortorder'] = $sortorder;
1586 $thispageurl->param('qsortorder', $sortorder);
1587 } else {
1588 $pagevars['qsortorderdecoded'] = $sortoptions['typealpha'];
1589 $pagevars['qsortorder'] = 'typealpha';
1592 $defaultcategory = question_make_default_categories($contexts->all());
1594 $contextlistarr = array();
1595 foreach ($contexts->having_one_edit_tab_cap($edittab) as $context){
1596 $contextlistarr[] = "'$context->id'";
1598 $contextlist = join($contextlistarr, ' ,');
1599 if (!empty($pagevars['cat'])){
1600 $catparts = explode(',', $pagevars['cat']);
1601 if (!$catparts[0] || (FALSE !== array_search($catparts[1], $contextlistarr)) ||
1602 !$DB->count_records_select("question_categories", "id = ? AND contextid = ?", array($catparts[0], $catparts[1]))) {
1603 print_error('invalidcategory', 'quiz');
1605 } else {
1606 $category = $defaultcategory;
1607 $pagevars['cat'] = "$category->id,$category->contextid";
1610 if(($recurse = optional_param('recurse', -1, PARAM_BOOL)) != -1) {
1611 $pagevars['recurse'] = $recurse;
1612 $thispageurl->param('recurse', $recurse);
1613 } else {
1614 $pagevars['recurse'] = 1;
1617 if(($showhidden = optional_param('showhidden', -1, PARAM_BOOL)) != -1) {
1618 $pagevars['showhidden'] = $showhidden;
1619 $thispageurl->param('showhidden', $showhidden);
1620 } else {
1621 $pagevars['showhidden'] = 0;
1624 if(($showquestiontext = optional_param('showquestiontext', -1, PARAM_BOOL)) != -1) {
1625 $pagevars['showquestiontext'] = $showquestiontext;
1626 $thispageurl->param('showquestiontext', $showquestiontext);
1627 } else {
1628 $pagevars['showquestiontext'] = 0;
1631 //category list page
1632 $pagevars['cpage'] = optional_param('cpage', 1, PARAM_INT);
1633 if ($pagevars['cpage'] != 1){
1634 $thispageurl->param('cpage', $pagevars['cpage']);
1637 return array($thispageurl, $contexts, $cmid, $cm, $module, $pagevars);
1641 * Required for legacy reasons. Was originally global then changed to class static
1642 * as of Moodle 2.0
1644 $QUESTION_EDITTABCAPS = question_edit_contexts::$CAPS;
1647 * Make sure user is logged in as required in this context.
1649 function require_login_in_context($contextorid = null){
1650 global $DB, $CFG;
1651 if (!is_object($contextorid)){
1652 $context = get_context_instance_by_id($contextorid);
1653 } else {
1654 $context = $contextorid;
1656 if ($context && ($context->contextlevel == CONTEXT_COURSE)) {
1657 require_login($context->instanceid);
1658 } else if ($context && ($context->contextlevel == CONTEXT_MODULE)) {
1659 if ($cm = $DB->get_record('course_modules',array('id' =>$context->instanceid))) {
1660 if (!$course = $DB->get_record('course', array('id' => $cm->course))) {
1661 print_error('invalidcourseid');
1663 require_course_login($course, true, $cm);
1665 } else {
1666 print_error('invalidcoursemodule');
1668 } else if ($context && ($context->contextlevel == CONTEXT_SYSTEM)) {
1669 if (!empty($CFG->forcelogin)) {
1670 require_login();
1673 } else {
1674 require_login();
1679 * Print a form to let the user choose which question type to add.
1680 * When the form is submitted, it goes to the question.php script.
1681 * @param $hiddenparams hidden parameters to add to the form, in addition to
1682 * the qtype radio buttons.
1684 function print_choose_qtype_to_add_form($hiddenparams) {
1685 global $CFG, $QTYPES, $PAGE, $OUTPUT;
1686 $PAGE->requires->js('/question/qbank.js');
1687 echo '<div id="chooseqtypehead" class="hd">' . "\n";
1688 echo $OUTPUT->heading(get_string('chooseqtypetoadd', 'question'), 3);
1689 echo "</div>\n";
1690 echo '<div id="chooseqtype">' . "\n";
1691 echo '<form action="' . $CFG->wwwroot . '/question/question.php" method="get"><div id="qtypeformdiv">' . "\n";
1692 foreach ($hiddenparams as $name => $value) {
1693 echo '<input type="hidden" name="' . s($name) . '" value="' . s($value) . '" />' . "\n";
1695 echo "</div>\n";
1696 echo '<div class="qtypes">' . "\n";
1697 echo '<div class="instruction">' . get_string('selectaqtypefordescription', 'question') . "</div>\n";
1698 echo '<div class="realqtypes">' . "\n";
1699 $types = question_type_menu();
1700 $fakeqtypes = array();
1701 foreach ($types as $qtype => $localizedname) {
1702 if ($QTYPES[$qtype]->is_real_question_type()) {
1703 print_qtype_to_add_option($qtype, $localizedname);
1704 } else {
1705 $fakeqtypes[$qtype] = $localizedname;
1708 echo "</div>\n";
1709 echo '<div class="fakeqtypes">' . "\n";
1710 foreach ($fakeqtypes as $qtype => $localizedname) {
1711 print_qtype_to_add_option($qtype, $localizedname);
1713 echo "</div>\n";
1714 echo "</div>\n";
1715 echo '<div class="submitbuttons">' . "\n";
1716 echo '<input type="submit" value="' . get_string('next') . '" id="chooseqtype_submit" />' . "\n";
1717 echo '<input type="submit" id="chooseqtypecancel" name="addcancel" value="' . get_string('cancel') . '" />' . "\n";
1718 echo "</div></form>\n";
1719 echo "</div>\n";
1720 $PAGE->requires->js_function_call('qtype_chooser.init', array('chooseqtype'));
1724 * Private function used by the preceding one.
1725 * @param $qtype the question type.
1726 * @param $localizedname the localized name of this question type.
1728 function print_qtype_to_add_option($qtype, $localizedname) {
1729 global $QTYPES;
1730 echo '<div class="qtypeoption">' . "\n";
1731 echo '<label for="qtype_' . $qtype . '">';
1732 echo '<input type="radio" name="qtype" id="qtype_' . $qtype . '" value="' . $qtype . '" />';
1733 echo '<span class="qtypename">';
1734 $fakequestion = new stdClass;
1735 $fakequestion->qtype = $qtype;
1736 print_question_icon($fakequestion);
1737 echo $localizedname . '</span><span class="qtypesummary">' . get_string($qtype . 'summary', 'qtype_' . $qtype);
1738 echo "</span></label>\n";
1739 echo "</div>\n";
1743 * Print a button for creating a new question. This will open question/addquestion.php,
1744 * which in turn goes to question/question.php before getting back to $params['returnurl']
1745 * (by default the question bank screen).
1747 * @param integer $categoryid The id of the category that the new question should be added to.
1748 * @param array $params Other paramters to add to the URL. You need either $params['cmid'] or
1749 * $params['courseid'], and you should probably set $params['returnurl']
1750 * @param string $caption the text to display on the button.
1751 * @param string $tooltip a tooltip to add to the button (optional).
1752 * @param boolean $disabled if true, the button will be disabled.
1754 function create_new_question_button($categoryid, $params, $caption, $tooltip = '', $disabled = false) {
1755 global $CFG, $PAGE, $OUTPUT;
1756 static $choiceformprinted = false;
1757 $params['category'] = $categoryid;
1758 $url = new moodle_url('/question/addquestion.php', $params);
1759 echo $OUTPUT->single_button($url, $caption, 'get', array('disabled'=>$disabled, 'title'=>$tooltip));
1761 $PAGE->requires->yui2_lib('dragdrop');
1762 $PAGE->requires->yui2_lib('container');
1763 if (!$choiceformprinted) {
1764 echo '<div id="qtypechoicecontainer">';
1765 print_choose_qtype_to_add_form(array());
1766 echo "</div>\n";
1767 $choiceformprinted = true;