Merge branch 'wip-mdl-29079-m20' of git://github.com/rajeshtaneja/moodle into MOODLE_...
[moodle.git] / question / editlib.php
blob860af692e31bf9514bfee0b0de5b88c35a877a78
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.
159 public function display_header() {
160 echo '<th class="header ' . $this->get_classes() . '" scope="col">';
161 $sortable = $this->is_sortable();
162 $name = $this->get_name();
163 $title = $this->get_title();
164 $tip = $this->get_title_tip();
165 if (is_array($sortable)) {
166 if ($title) {
167 echo '<div class="title">' . $title . '</div>';
169 $links = array();
170 foreach ($sortable as $subsort => $details) {
171 $links[] = $this->make_sort_link($name . '_' . $subsort,
172 $details['title'], '', !empty($details['reverse']));
174 echo '<div class="sorters">' . implode(' / ', $links) . '</div>';
175 } else if ($sortable) {
176 echo $this->make_sort_link($name, $title, $tip);
177 } else {
178 if ($tip) {
179 echo '<span title="' . $tip . '">';
181 echo $title;
182 if ($tip) {
183 echo '</span>';
186 echo "</th>\n";
190 * Title for this column. Not used if is_sortable returns an array.
191 * @param object $question the row from the $question table, augmented with extra information.
192 * @param string $rowclasses CSS class names that should be applied to this row of output.
194 abstract protected function get_title();
197 * @return string a fuller version of the name. Use this when get_title() returns
198 * something very short, and you want a longer version as a tool tip.
200 protected function get_title_tip() {
201 return '';
205 * Get a link that changes the sort order, and indicates the current sort state.
206 * @param $name internal name used for this type of sorting.
207 * @param $currentsort the current sort order -1, 0, 1 for descending, none, ascending.
208 * @param $title the link text.
209 * @param $defaultreverse whether the default sort order for this column is descending, rather than ascending.
210 * @return string HTML fragment.
212 protected function make_sort_link($sort, $title, $tip, $defaultreverse = false) {
213 $currentsort = $this->qbank->get_primary_sort_order($sort);
214 $newsortreverse = $defaultreverse;
215 if ($currentsort) {
216 $newsortreverse = $currentsort > 0;
218 if (!$tip) {
219 $tip = $title;
221 if ($newsortreverse) {
222 $tip = get_string('sortbyxreverse', '', $tip);
223 } else {
224 $tip = get_string('sortbyx', '', $tip);
226 $link = '<a href="' . $this->qbank->new_sort_url($sort, $newsortreverse) . '" title="' . $tip . '">';
227 $link .= $title;
228 if ($currentsort) {
229 $link .= $this->get_sort_icon($currentsort < 0);
231 $link .= '</a>';
232 return $link;
236 * Get an icon representing the corrent sort state.
237 * @param $reverse sort is descending, not ascending.
238 * @return string HTML image tag.
240 protected function get_sort_icon($reverse) {
241 global $OUTPUT;
242 if ($reverse) {
243 return ' <img src="' . $OUTPUT->pix_url('t/up') . '" alt="' . get_string('desc') . '" />';
244 } else {
245 return ' <img src="' . $OUTPUT->pix_url('t/down') . '" alt="' . get_string('asc') . '" />';
250 * Output this column.
251 * @param object $question the row from the $question table, augmented with extra information.
252 * @param string $rowclasses CSS class names that should be applied to this row of output.
254 public function display($question, $rowclasses) {
255 $this->display_start($question, $rowclasses);
256 $this->display_content($question, $rowclasses);
257 $this->display_end($question, $rowclasses);
260 protected function display_start($question, $rowclasses) {
261 echo '<td class="' . $this->get_classes() . '">';
265 * @return string the CSS classes to apply to every cell in this column.
267 protected function get_classes() {
268 $classes = $this->get_extra_classes();
269 $classes[] = $this->get_name();
270 return implode(' ', $classes);
274 * @param object $question the row from the $question table, augmented with extra information.
275 * @return string internal name for this column. Used as a CSS class name,
276 * and to store information about the current sort. Must match PARAM_ALPHA.
278 abstract public function get_name();
281 * @return array any extra class names you would like applied to every cell in this column.
283 public function get_extra_classes() {
284 return array();
288 * Output the contents of this column.
289 * @param object $question the row from the $question table, augmented with extra information.
290 * @param string $rowclasses CSS class names that should be applied to this row of output.
292 abstract protected function display_content($question, $rowclasses);
294 protected function display_end($question, $rowclasses) {
295 echo "</td>\n";
299 * Return an array 'table_alias' => 'JOIN clause' to bring in any data that
300 * this column required.
302 * The return values for all the columns will be checked. It is OK if two
303 * columns join in the same table with the same alias and identical JOIN clauses.
304 * If to columns try to use the same alias with different joins, you get an error.
305 * The only table included by default is the question table, which is aliased to 'q'.
307 * It is importnat that your join simply adds additional data (or NULLs) to the
308 * existing rows of the query. It must not cause additional rows.
310 * @return array 'table_alias' => 'JOIN clause'
312 public function get_extra_joins() {
313 return array();
317 * @return array fields required. use table alias 'q' for the question table, or one of the
318 * ones from get_extra_joins. Every field requested must specify a table prefix.
320 public function get_required_fields() {
321 return array();
325 * Can this column be sorted on? You can return either:
326 * + false for no (the default),
327 * + a field name, if sorting this column corresponds to sorting on that datbase field.
328 * + an array of subnames to sort on as follows
329 * return array(
330 * 'firstname' => array('field' => 'uc.firstname', 'title' => get_string('firstname')),
331 * 'lastname' => array('field' => 'uc.lastname', 'field' => get_string('lastname')),
332 * );
333 * As well as field, and field, you can also add 'revers' => 1 if you want the default sort
334 * order to be DESC.
335 * @return mixed as above.
337 public function is_sortable() {
338 return false;
342 * Helper method for building sort clauses.
343 * @param boolean $reverse whether the normal direction should be reversed.
344 * @param string $normaldir 'ASC' or 'DESC'
345 * @return string 'ASC' or 'DESC'
347 protected function sortorder($reverse) {
348 if ($reverse) {
349 return ' DESC';
350 } else {
351 return ' ASC';
356 * @param $reverse Whether to sort in the reverse of the default sort order.
357 * @param $subsort if is_sortable returns an array of subnames, then this will be
358 * one of those. Otherwise will be empty.
359 * @return string some SQL to go in the order by clause.
361 public function sort_expression($reverse, $subsort) {
362 $sortable = $this->is_sortable();
363 if (is_array($sortable)) {
364 if (array_key_exists($subsort, $sortable)) {
365 return $sortable[$subsort]['field'] . $this->sortorder($reverse, !empty($sortable[$subsort]['reverse']));
366 } else {
367 throw new coding_exception('Unexpected $subsort type: ' . $subsort);
369 } else if ($sortable) {
370 return $sortable . $this->sortorder($reverse);
371 } else {
372 throw new coding_exception('sort_expression called on a non-sortable column.');
378 * A column with a checkbox for each question with name q{questionid}.
380 class question_bank_checkbox_column extends question_bank_column_base {
381 protected $strselect;
382 protected $firstrow = true;
384 public function init() {
385 $this->strselect = get_string('select', 'quiz');
388 public function get_name() {
389 return 'checkbox';
392 protected function get_title() {
393 return '<input type="checkbox" disabled="disabled" id="qbheadercheckbox" />';
396 protected function get_title_tip() {
397 return get_string('selectquestionsforbulk', 'question');
400 protected function display_content($question, $rowclasses) {
401 global $PAGE;
402 echo '<input title="' . $this->strselect . '" type="checkbox" name="q' .
403 $question->id . '" id="checkq' . $question->id . '" value="1"/>';
404 if ($this->firstrow) {
405 $PAGE->requires->js_function_call('question_bank.init_checkbox_column', array(get_string('selectall'),
406 get_string('deselectall'), 'checkq' . $question->id));
407 $this->firstrow = false;
411 public function get_required_fields() {
412 return array('q.id');
417 * A column type for the name of the question type.
419 class question_bank_question_type_column extends question_bank_column_base {
420 public function get_name() {
421 return 'qtype';
424 protected function get_title() {
425 return get_string('qtypeveryshort', 'question');
428 protected function get_title_tip() {
429 return get_string('questiontype', 'question');
432 protected function display_content($question, $rowclasses) {
433 echo print_question_icon($question);
436 public function get_required_fields() {
437 return array('q.qtype');
440 public function is_sortable() {
441 return 'q.qtype';
446 * A column type for the name of the question name.
448 class question_bank_question_name_column extends question_bank_column_base {
449 protected $checkboxespresent = null;
451 public function get_name() {
452 return 'questionname';
455 protected function get_title() {
456 return get_string('question');
459 protected function label_for($question) {
460 if (is_null($this->checkboxespresent)) {
461 $this->checkboxespresent = $this->qbank->has_column('checkbox');
463 if ($this->checkboxespresent) {
464 return 'checkq' . $question->id;
465 } else {
466 return '';
470 protected function display_content($question, $rowclasses) {
471 $labelfor = $this->label_for($question);
472 if ($labelfor) {
473 echo '<label for="' . $labelfor . '">';
475 echo format_string($question->name);
476 if ($labelfor) {
477 echo '</label>';
481 public function get_required_fields() {
482 return array('q.id', 'q.name');
485 public function is_sortable() {
486 return 'q.name';
491 * A column type for the name of the question creator.
493 class question_bank_creator_name_column extends question_bank_column_base {
494 public function get_name() {
495 return 'creatorname';
498 protected function get_title() {
499 return get_string('createdby', 'question');
502 protected function display_content($question, $rowclasses) {
503 if (!empty($question->creatorfirstname) && !empty($question->creatorlastname)) {
504 $u = new stdClass;
505 $u->firstname = $question->creatorfirstname;
506 $u->lastname = $question->creatorlastname;
507 echo fullname($u);
511 public function get_extra_joins() {
512 return array('uc' => 'LEFT JOIN {user} uc ON uc.id = q.createdby');
515 public function get_required_fields() {
516 return array('uc.firstname AS creatorfirstname', 'uc.lastname AS creatorlastname');
519 public function is_sortable() {
520 return array(
521 'firstname' => array('field' => 'uc.firstname', 'title' => get_string('firstname')),
522 'lastname' => array('field' => 'uc.lastname', 'title' => get_string('lastname')),
528 * A column type for the name of the question last modifier.
530 class question_bank_modifier_name_column extends question_bank_column_base {
531 public function get_name() {
532 return 'modifiername';
535 protected function get_title() {
536 return get_string('lastmodifiedby', 'question');
539 protected function display_content($question, $rowclasses) {
540 if (!empty($question->modifierfirstname) && !empty($question->modifierlastname)) {
541 $u = new stdClass;
542 $u->firstname = $question->modifierfirstname;
543 $u->lastname = $question->modifierlastname;
544 echo fullname($u);
548 public function get_extra_joins() {
549 return array('um' => 'LEFT JOIN {user} um ON um.id = q.modifiedby');
552 public function get_required_fields() {
553 return array('um.firstname AS modifierfirstname', 'um.lastname AS modifierlastname');
556 public function is_sortable() {
557 return array(
558 'firstname' => array('field' => 'um.firstname', 'title' => get_string('firstname')),
559 'lastname' => array('field' => 'um.lastname', 'title' => get_string('lastname')),
565 * A base class for actions that are an icon that lets you manipulate the question in some way.
567 abstract class question_bank_action_column_base extends question_bank_column_base {
569 protected function get_title() {
570 return '&#160;';
573 public function get_extra_classes() {
574 return array('iconcol');
577 protected function print_icon($icon, $title, $url) {
578 global $OUTPUT;
579 echo '<a title="' . $title . '" href="' . $url . '">
580 <img src="' . $OUTPUT->pix_url($icon) . '" class="iconsmall" alt="' . $title . '" /></a>';
583 public function get_required_fields() {
584 return array('q.id');
588 class question_bank_edit_action_column extends question_bank_action_column_base {
589 protected $stredit;
590 protected $strview;
592 public function init() {
593 parent::init();
594 $this->stredit = get_string('edit');
595 $this->strview = get_string('view');
598 public function get_name() {
599 return 'editaction';
602 protected function display_content($question, $rowclasses) {
603 if (question_has_capability_on($question, 'edit') ||
604 question_has_capability_on($question, 'move')) {
605 $this->print_icon('t/edit', $this->stredit, $this->qbank->edit_question_url($question->id));
606 } else {
607 $this->print_icon('i/info', $this->strview, $this->qbank->edit_question_url($question->id));
612 class question_bank_preview_action_column extends question_bank_action_column_base {
613 protected $strpreview;
615 public function init() {
616 parent::init();
617 $this->strpreview = get_string('preview');
620 public function get_name() {
621 return 'previewaction';
624 protected function display_content($question, $rowclasses) {
625 global $OUTPUT;
626 if (question_has_capability_on($question, 'use')) {
627 // Build the icon.
628 $image = $OUTPUT->pix_icon('t/preview', $this->strpreview);
630 $link = new moodle_url($this->qbank->preview_question_url($question->id));
631 parse_str(QUESTION_PREVIEW_POPUP_OPTIONS, $options);
632 $action = new popup_action('click', $link, 'questionpreview', $options);
634 echo $OUTPUT->action_link($link, $image, $action, array('title' => $this->strpreview));
638 public function get_required_fields() {
639 return array('q.id');
643 class question_bank_move_action_column extends question_bank_action_column_base {
644 protected $strmove;
646 public function init() {
647 parent::init();
648 $this->strmove = get_string('move');
651 public function get_name() {
652 return 'moveaction';
655 protected function display_content($question, $rowclasses) {
656 if (question_has_capability_on($question, 'move')) {
657 $this->print_icon('t/move', $this->strmove, $this->qbank->move_question_url($question->id));
663 * action to delete (or hide) a question, or restore a previously hidden question.
665 class question_bank_delete_action_column extends question_bank_action_column_base {
666 protected $strdelete;
667 protected $strrestore;
669 public function init() {
670 parent::init();
671 $this->strdelete = get_string('delete');
672 $this->strrestore = get_string('restore');
675 public function get_name() {
676 return 'deleteaction';
679 protected function display_content($question, $rowclasses) {
680 if (question_has_capability_on($question, 'edit')) {
681 if ($question->hidden) {
682 $url = new moodle_url($this->qbank->base_url(), array('unhide' => $question->id, 'sesskey'=>sesskey()));
683 $this->print_icon('t/restore', $this->strrestore, $url);
684 } else {
685 $url = new moodle_url($this->qbank->base_url(), array('deleteselected' => $question->id, 'q' . $question->id => 1, 'sesskey'=>sesskey()));
686 $this->print_icon('t/delete', $this->strdelete, $url);
691 public function get_required_fields() {
692 return array('q.id', 'q.hidden');
697 * Base class for 'columns' that are actually displayed as a row following the main question row.
699 abstract class question_bank_row_base extends question_bank_column_base {
700 public function is_extra_row() {
701 return true;
704 protected function display_start($question, $rowclasses) {
705 if ($rowclasses) {
706 echo '<tr class="' . $rowclasses . '">' . "\n";
707 } else {
708 echo "<tr>\n";
710 echo '<td colspan="' . $this->qbank->get_column_count() . '" class="' . $this->get_name() . '">';
713 protected function display_end($question, $rowclasses) {
714 echo "</td></tr>\n";
719 * A column type for the name of the question name.
721 class question_bank_question_text_row extends question_bank_row_base {
722 protected $formatoptions;
724 protected function init() {
725 $this->formatoptions = new stdClass;
726 $this->formatoptions->noclean = true;
727 $this->formatoptions->para = false;
730 public function get_name() {
731 return 'questiontext';
734 protected function get_title() {
735 return get_string('questiontext', 'question');
738 protected function display_content($question, $rowclasses) {
739 $text = format_text($question->questiontext, $question->questiontextformat,
740 $this->formatoptions, $this->qbank->get_courseid());
741 if ($text == '') {
742 $text = '&#160;';
744 echo $text;
747 public function get_required_fields() {
748 return array('q.questiontext', 'q.questiontextformat');
753 * This class prints a view of the question bank, including
754 * + Some controls to allow users to to select what is displayed.
755 * + A list of questions as a table.
756 * + Further controls to do things with the questions.
758 * This class gives a basic view, and provides plenty of hooks where subclasses
759 * can override parts of the display.
761 * The list of questions presented as a table is generated by creating a list of
762 * question_bank_column objects, one for each 'column' to be displayed. These
763 * manage
764 * + outputting the contents of that column, given a $question object, but also
765 * + generating the right fragments of SQL to ensure the necessary data is present,
766 * and sorted in the right order.
767 * + outputting table headers.
769 class question_bank_view {
770 const MAX_SORTS = 3;
772 protected $baseurl;
773 protected $editquestionurl;
774 protected $quizorcourseid;
775 protected $contexts;
776 protected $cm;
777 protected $course;
778 protected $knowncolumntypes;
779 protected $visiblecolumns;
780 protected $extrarows;
781 protected $requiredcolumns;
782 protected $sort;
783 protected $lastchangedid;
784 protected $countsql;
785 protected $loadsql;
786 protected $sqlparams;
788 public function __construct($contexts, $pageurl, $course, $cm = null) {
789 global $CFG, $PAGE;
791 $this->contexts = $contexts;
792 $this->baseurl = $pageurl;
793 $this->course = $course;
794 $this->cm = $cm;
796 if (!empty($cm) && $cm->modname == 'quiz') {
797 $this->quizorcourseid = '&amp;quizid=' . $cm->instance;
798 } else {
799 $this->quizorcourseid = '&amp;courseid=' .$this->course->id;
802 // Create the url of the new question page to forward to.
803 $returnurl = str_replace($CFG->wwwroot, '', $pageurl->out(false));
804 $this->editquestionurl = new moodle_url('/question/question.php',
805 array('returnurl' => $returnurl));
806 if ($cm !== null){
807 $this->editquestionurl->param('cmid', $cm->id);
808 } else {
809 $this->editquestionurl->param('courseid', $this->course->id);
812 $this->lastchangedid = optional_param('lastchanged',0,PARAM_INT);
814 $this->init_column_types();
815 $this->init_columns($this->wanted_columns());
816 $this->init_sort();
818 $PAGE->requires->yui2_lib('container');
821 protected function wanted_columns() {
822 $columns = array('checkbox', 'qtype', 'questionname', 'editaction',
823 'previewaction', 'moveaction', 'deleteaction', 'creatorname',
824 'modifiername');
825 if (optional_param('qbshowtext', false, PARAM_BOOL)) {
826 $columns[] = 'questiontext';
828 return $columns;
831 protected function known_field_types() {
832 return array(
833 new question_bank_checkbox_column($this),
834 new question_bank_question_type_column($this),
835 new question_bank_question_name_column($this),
836 new question_bank_creator_name_column($this),
837 new question_bank_modifier_name_column($this),
838 new question_bank_edit_action_column($this),
839 new question_bank_preview_action_column($this),
840 new question_bank_move_action_column($this),
841 new question_bank_delete_action_column($this),
842 new question_bank_question_text_row($this),
846 protected function init_column_types() {
847 $this->knowncolumntypes = array();
848 foreach ($this->known_field_types() as $col) {
849 $this->knowncolumntypes[$col->get_name()] = $col;
853 protected function init_columns($wanted) {
854 $this->visiblecolumns = array();
855 $this->extrarows = array();
856 foreach ($wanted as $colname) {
857 if (!isset($this->knowncolumntypes[$colname])) {
858 throw new coding_exception('Unknown column type ' . $colname . ' requested in init columns.');
860 $column = $this->knowncolumntypes[$colname];
861 if ($column->is_extra_row()) {
862 $this->extrarows[$colname] = $column;
863 } else {
864 $this->visiblecolumns[$colname] = $column;
867 $this->requiredcolumns = array_merge($this->visiblecolumns, $this->extrarows);
871 * @param string $colname a column internal name.
872 * @return boolean is this column included in the output?
874 public function has_column($colname) {
875 return isset($this->visiblecolumns[$colname]);
879 * @return integer The number of columns in the table.
881 public function get_column_count() {
882 return count($this->visiblecolumns);
885 public function get_courseid() {
886 return $this->course->id;
889 protected function init_sort() {
890 $this->init_sort_from_params();
891 if (empty($this->sort)) {
892 $this->sort = $this->default_sort();
897 * Deal with a sort name of the forum columnname, or colname_subsort by
898 * breaking it up, validating the bits that are presend, and returning them.
899 * If there is no subsort, then $subsort is returned as ''.
900 * @return array array($colname, $subsort).
902 protected function parse_subsort($sort) {
903 /// Do the parsing.
904 if (strpos($sort, '_') !== false) {
905 list($colname, $subsort) = explode('_', $sort, 2);
906 } else {
907 $colname = $sort;
908 $subsort = '';
910 /// Validate the column name.
911 if (!isset($this->knowncolumntypes[$colname]) || !$this->knowncolumntypes[$colname]->is_sortable()) {
912 for ($i = 1; $i <= question_bank_view::MAX_SORTS; $i++) {
913 $this->baseurl->remove_params('qbs' . $i);
915 throw new moodle_exception('unknownsortcolumn', '', $link = $this->baseurl->out(), $colname);
917 /// Validate the subsort, if present.
918 if ($subsort) {
919 $subsorts = $this->knowncolumntypes[$colname]->is_sortable();
920 if (!is_array($subsorts) || !isset($subsorts[$subsort])) {
921 throw new moodle_exception('unknownsortcolumn', '', $link = $this->baseurl->out(), $sort);
924 return array($colname, $subsort);
927 protected function init_sort_from_params() {
928 $this->sort = array();
929 for ($i = 1; $i <= question_bank_view::MAX_SORTS; $i++) {
930 if (!$sort = optional_param('qbs' . $i, '', PARAM_ALPHAEXT)) {
931 break;
933 // Work out the appropriate order.
934 $order = 1;
935 if ($sort[0] == '-') {
936 $order = -1;
937 $sort = substr($sort, 1);
938 if (!$sort) {
939 break;
942 // Deal with subsorts.
943 list($colname, $subsort) = $this->parse_subsort($sort);
944 $this->requiredcolumns[$colname] = $this->knowncolumntypes[$colname];
945 $this->sort[$sort] = $order;
949 protected function sort_to_params($sorts) {
950 $params = array();
951 $i = 0;
952 foreach ($sorts as $sort => $order) {
953 $i += 1;
954 if ($order < 0) {
955 $sort = '-' . $sort;
957 $params['qbs' . $i] = $sort;
959 return $params;
962 protected function default_sort() {
963 return array('qtype' => 1, 'questionname' => 1);
967 * @param $sort a column or column_subsort name.
968 * @return integer the current sort order for this column -1, 0, 1
970 public function get_primary_sort_order($sort) {
971 $order = reset($this->sort);
972 $primarysort = key($this->sort);
973 if ($sort == $primarysort) {
974 return $order;
975 } else {
976 return 0;
981 * Get a URL to redisplay the page with a new sort for the question bank.
982 * @param string $sort the column, or column_subsort to sort on.
983 * @param boolean $newsortreverse whether to sort in reverse order.
984 * @return string The new URL.
986 public function new_sort_url($sort, $newsortreverse) {
987 if ($newsortreverse) {
988 $order = -1;
989 } else {
990 $order = 1;
992 // Tricky code to add the new sort at the start, removing it from where it was before, if it was present.
993 $newsort = array_reverse($this->sort);
994 if (isset($newsort[$sort])) {
995 unset($newsort[$sort]);
997 $newsort[$sort] = $order;
998 $newsort = array_reverse($newsort);
999 if (count($newsort) > question_bank_view::MAX_SORTS) {
1000 $newsort = array_slice($newsort, 0, question_bank_view::MAX_SORTS, true);
1002 return $this->baseurl->out(true, $this->sort_to_params($newsort));
1005 protected function build_query_sql($category, $recurse, $showhidden) {
1006 global $DB;
1008 /// Get the required tables.
1009 $joins = array();
1010 foreach ($this->requiredcolumns as $column) {
1011 $extrajoins = $column->get_extra_joins();
1012 foreach ($extrajoins as $prefix => $join) {
1013 if (isset($joins[$prefix]) && $joins[$prefix] != $join) {
1014 throw new coding_exception('Join ' . $join . ' conflicts with previous join ' . $joins[$prefix]);
1016 $joins[$prefix] = $join;
1020 /// Get the required fields.
1021 $fields = array('q.hidden', 'q.category');
1022 foreach ($this->visiblecolumns as $column) {
1023 $fields = array_merge($fields, $column->get_required_fields());
1025 foreach ($this->extrarows as $row) {
1026 $fields = array_merge($fields, $row->get_required_fields());
1028 $fields = array_unique($fields);
1030 /// Build the order by clause.
1031 $sorts = array();
1032 foreach ($this->sort as $sort => $order) {
1033 list($colname, $subsort) = $this->parse_subsort($sort);
1034 $sorts[] = $this->knowncolumntypes[$colname]->sort_expression($order < 0, $subsort);
1037 /// Build the where clause.
1038 $tests = array('parent = 0');
1040 if (!$showhidden) {
1041 $tests[] = 'hidden = 0';
1044 if ($recurse) {
1045 $categoryids = explode(',', question_categorylist($category->id));
1046 } else {
1047 $categoryids = array($category->id);
1049 list($catidtest, $params) = $DB->get_in_or_equal($categoryids, SQL_PARAMS_NAMED, 'cat');
1050 $tests[] = 'q.category ' . $catidtest;
1051 $this->sqlparams = $params;
1053 /// Build the SQL.
1054 $sql = ' FROM {question} q ' . implode(' ', $joins);
1055 $sql .= ' WHERE ' . implode(' AND ', $tests);
1056 $this->countsql = 'SELECT count(1)' . $sql;
1057 $this->loadsql = 'SELECT ' . implode(', ', $fields) . $sql . ' ORDER BY ' . implode(', ', $sorts);
1058 $this->sqlparams = $params;
1061 protected function get_question_count() {
1062 global $DB;
1063 return $DB->count_records_sql($this->countsql, $this->sqlparams);
1066 protected function load_page_questions($page, $perpage) {
1067 global $DB;
1068 $questions = $DB->get_recordset_sql($this->loadsql, $this->sqlparams, $page*$perpage, $perpage);
1069 if (!$questions->valid()) {
1070 /// No questions on this page. Reset to page 0.
1071 $questions = $DB->get_recordset_sql($this->loadsql, $this->sqlparams, 0, $perpage);
1073 return $questions;
1076 public function base_url() {
1077 return $this->baseurl;
1080 public function edit_question_url($questionid) {
1081 return $this->editquestionurl->out(true, array('id' => $questionid));
1084 public function move_question_url($questionid) {
1085 return $this->editquestionurl->out(true, array('id' => $questionid, 'movecontext' => 1));
1088 public function preview_question_url($questionid) {
1089 global $CFG;
1090 return $CFG->wwwroot . '/question/preview.php?id=' . $questionid . '&amp;courseid=' . $this->course->id;
1094 * Shows the question bank editing interface.
1096 * The function also processes a number of actions:
1098 * Actions affecting the question pool:
1099 * move Moves a question to a different category
1100 * deleteselected Deletes the selected questions from the category
1101 * Other actions:
1102 * category Chooses the category
1103 * displayoptions Sets display options
1105 public function display($tabname, $page, $perpage, $cat,
1106 $recurse, $showhidden, $showquestiontext) {
1107 global $PAGE, $OUTPUT;
1109 if ($this->process_actions_needing_ui()) {
1110 return;
1113 $PAGE->requires->js('/question/qbank.js');
1115 // Category selection form
1116 echo $OUTPUT->heading(get_string('questionbank', 'question'), 2);
1118 $this->display_category_form($this->contexts->having_one_edit_tab_cap($tabname),
1119 $this->baseurl, $cat);
1120 $this->display_options($recurse, $showhidden, $showquestiontext);
1122 if (!$category = $this->get_current_category($cat)) {
1123 return;
1125 $this->print_category_info($category);
1127 // continues with list of questions
1128 $this->display_question_list($this->contexts->having_one_edit_tab_cap($tabname),
1129 $this->baseurl, $cat, $this->cm,
1130 $recurse, $page, $perpage, $showhidden, $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, $showhidden, $showquestiontext) {
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', 'qbshowtext'));
1188 $this->display_category_form_checkbox('recurse', $recurse, get_string('recurse', 'quiz'));
1189 $this->display_category_form_checkbox('showhidden', $showhidden, get_string('showhidden', 'quiz'));
1190 $this->display_category_form_checkbox('qbshowtext', $showquestiontext, 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, $value, $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 ($value) {
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 $showquestiontext = false, $addcontexts = array()) {
1236 global $CFG, $DB, $OUTPUT;
1238 $category = $this->get_current_category($categoryandcontext);
1240 $cmoptions = new stdClass;
1241 $cmoptions->hasattempts = !empty($this->quizhasattempts);
1243 $strselectall = get_string("selectall", "quiz");
1244 $strselectnone = get_string("selectnone", "quiz");
1245 $strdelete = get_string("delete");
1247 list($categoryid, $contextid) = explode(',', $categoryandcontext);
1248 $catcontext = get_context_instance_by_id($contextid);
1250 $canadd = has_capability('moodle/question:add', $catcontext);
1251 $caneditall =has_capability('moodle/question:editall', $catcontext);
1252 $canuseall =has_capability('moodle/question:useall', $catcontext);
1253 $canmoveall =has_capability('moodle/question:moveall', $catcontext);
1255 $this->create_new_question_form($category, $canadd);
1257 $this->build_query_sql($category, $recurse, $showhidden);
1258 $totalnumber = $this->get_question_count();
1259 if ($totalnumber == 0) {
1260 return;
1263 $questions = $this->load_page_questions($page, $perpage);
1265 echo '<div class="categorypagingbarcontainer">';
1266 $pageing_url = new moodle_url('edit.php');
1267 $r = $pageing_url->params($pageurl->params());
1268 $pagingbar = new paging_bar($totalnumber, $page, $perpage, $pageing_url);
1269 $pagingbar->pagevar = 'qpage';
1270 echo $OUTPUT->render($pagingbar);
1271 echo '</div>';
1273 echo '<form method="post" action="edit.php">';
1274 echo '<fieldset class="invisiblefieldset" style="display: block;">';
1275 echo '<input type="hidden" name="sesskey" value="'.sesskey().'" />';
1276 echo html_writer::input_hidden_params($pageurl);
1278 echo '<div class="categoryquestionscontainer">';
1279 $this->start_table();
1280 $rowcount = 0;
1281 foreach ($questions as $question) {
1282 $this->print_table_row($question, $rowcount);
1283 $rowcount += 1;
1285 $this->end_table();
1286 echo "</div>\n";
1288 echo '<div class="categorypagingbarcontainer pagingbottom">';
1289 echo $OUTPUT->render($pagingbar);
1290 if ($totalnumber > DEFAULT_QUESTIONS_PER_PAGE) {
1291 if ($perpage == DEFAULT_QUESTIONS_PER_PAGE) {
1292 $url = new moodle_url('edit.php', ($pageurl->params()+array('qperpage'=>1000)));
1293 $showall = '<a href="'.$url.'">'.get_string('showall', 'moodle', $totalnumber).'</a>';
1294 } else {
1295 $url = new moodle_url('edit.php', ($pageurl->params()+array('qperpage'=>DEFAULT_QUESTIONS_PER_PAGE)));
1296 $showall = '<a href="'.$url.'">'.get_string('showperpage', 'moodle', DEFAULT_QUESTIONS_PER_PAGE).'</a>';
1298 echo "<div class='paging'>$showall</div>";
1300 echo '</div>';
1302 echo '<div class="modulespecificbuttonscontainer">';
1303 if ($caneditall || $canmoveall || $canuseall){
1304 echo '<strong>&nbsp;'.get_string('withselected', 'quiz').':</strong><br />';
1306 if (function_exists('module_specific_buttons')) {
1307 echo module_specific_buttons($this->cm->id,$cmoptions);
1310 // print delete and move selected question
1311 if ($caneditall) {
1312 echo '<input type="submit" name="deleteselected" value="' . $strdelete . "\" />\n";
1315 if ($canmoveall && count($addcontexts)) {
1316 echo '<input type="submit" name="move" value="'.get_string('moveto', 'quiz')."\" />\n";
1317 question_category_select_menu($addcontexts, false, 0, "$category->id,$category->contextid");
1320 if (function_exists('module_specific_controls') && $canuseall) {
1321 $modulespecific = module_specific_controls($totalnumber, $recurse, $category, $this->cm->id,$cmoptions);
1322 if(!empty($modulespecific)){
1323 echo "<hr />$modulespecific";
1327 echo "</div>\n";
1329 echo '</fieldset>';
1330 echo "</form>\n";
1333 protected function start_table() {
1334 echo '<table id="categoryquestions">' . "\n";
1335 echo "<thead>\n";
1336 $this->print_table_headers();
1337 echo "</thead>\n";
1338 echo "<tbody>\n";
1341 protected function end_table() {
1342 echo "</tbody>\n";
1343 echo "</table>\n";
1346 protected function print_table_headers() {
1347 echo "<tr>\n";
1348 foreach ($this->visiblecolumns as $column) {
1349 $column->display_header();
1351 echo "</tr>\n";
1354 protected function get_row_classes($question, $rowcount) {
1355 $classes = array();
1356 if ($question->hidden) {
1357 $classes[] = 'dimmed_text';
1359 if ($question->id == $this->lastchangedid) {
1360 $classes[] ='highlight';
1362 if (!empty($this->extrarows)) {
1363 $classes[] = 'r' . ($rowcount % 2);
1365 return $classes;
1368 protected function print_table_row($question, $rowcount) {
1369 $rowclasses = implode(' ', $this->get_row_classes($question, $rowcount));
1370 if ($rowclasses) {
1371 echo '<tr class="' . $rowclasses . '">' . "\n";
1372 } else {
1373 echo "<tr>\n";
1375 foreach ($this->visiblecolumns as $column) {
1376 $column->display($question, $rowclasses);
1378 echo "</tr>\n";
1379 foreach ($this->extrarows as $row) {
1380 $row->display($question, $rowclasses);
1384 public function process_actions() {
1385 global $CFG, $DB;
1386 /// Now, check for commands on this page and modify variables as necessary
1387 if (optional_param('move', false, PARAM_BOOL) and confirm_sesskey()) {
1388 // Move selected questions to new category
1389 $category = required_param('category', PARAM_SEQUENCE);
1390 list($tocategoryid, $contextid) = explode(',', $category);
1391 if (! $tocategory = $DB->get_record('question_categories', array('id' => $tocategoryid, 'contextid' => $contextid))) {
1392 print_error('cannotfindcate', 'question');
1394 $tocontext = get_context_instance_by_id($contextid);
1395 require_capability('moodle/question:add', $tocontext);
1396 $rawdata = (array) data_submitted();
1397 $questionids = array();
1398 foreach ($rawdata as $key => $value) { // Parse input for question ids
1399 if (preg_match('!^q([0-9]+)$!', $key, $matches)) {
1400 $key = $matches[1];
1401 $questionids[] = $key;
1404 if ($questionids) {
1405 list($usql, $params) = $DB->get_in_or_equal($questionids);
1406 $sql = "";
1407 $questions = $DB->get_records_sql("
1408 SELECT q.*, c.contextid
1409 FROM {question} q
1410 JOIN {question_categories} c ON c.id = q.category
1411 WHERE q.id $usql", $params);
1412 foreach ($questions as $question){
1413 question_require_capability_on($question, 'move');
1415 question_move_questions_to_category($questionids, $tocategory->id);
1416 redirect($this->baseurl->out(false,
1417 array('category' => "$tocategoryid,$contextid")));
1421 if (optional_param('deleteselected', false, PARAM_BOOL)) { // delete selected questions from the category
1422 if (($confirm = optional_param('confirm', '', PARAM_ALPHANUM)) and confirm_sesskey()) { // teacher has already confirmed the action
1423 $deleteselected = required_param('deleteselected', PARAM_RAW);
1424 if ($confirm == md5($deleteselected)) {
1425 if ($questionlist = explode(',', $deleteselected)) {
1426 // for each question either hide it if it is in use or delete it
1427 foreach ($questionlist as $questionid) {
1428 $questionid = (int)$questionid;
1429 question_require_capability_on($questionid, 'edit');
1430 if ($DB->record_exists('quiz_question_instances', array('question' => $questionid))) {
1431 $DB->set_field('question', 'hidden', 1, array('id' => $questionid));
1432 } else {
1433 delete_question($questionid);
1437 redirect($this->baseurl);
1438 } else {
1439 print_error('invalidconfirm', 'question');
1444 // Unhide a question
1445 if(($unhide = optional_param('unhide', '', PARAM_INT)) and confirm_sesskey()) {
1446 question_require_capability_on($unhide, 'edit');
1447 $DB->set_field('question', 'hidden', 0, array('id' => $unhide));
1448 redirect($this->baseurl);
1452 public function process_actions_needing_ui() {
1453 global $DB, $OUTPUT;
1454 if (optional_param('deleteselected', false, PARAM_BOOL)) {
1455 // make a list of all the questions that are selected
1456 $rawquestions = $_REQUEST; // This code is called by both POST forms and GET links, so cannot use data_submitted.
1457 $questionlist = ''; // comma separated list of ids of questions to be deleted
1458 $questionnames = ''; // string with names of questions separated by <br /> with
1459 // an asterix in front of those that are in use
1460 $inuse = false; // set to true if at least one of the questions is in use
1461 foreach ($rawquestions as $key => $value) { // Parse input for question ids
1462 if (preg_match('!^q([0-9]+)$!', $key, $matches)) {
1463 $key = $matches[1];
1464 $questionlist .= $key.',';
1465 question_require_capability_on($key, 'edit');
1466 if ($DB->record_exists('quiz_question_instances', array('question' => $key))) {
1467 $questionnames .= '* ';
1468 $inuse = true;
1470 $questionnames .= $DB->get_field('question', 'name', array('id' => $key)) . '<br />';
1473 if (!$questionlist) { // no questions were selected
1474 redirect($this->baseurl);
1476 $questionlist = rtrim($questionlist, ',');
1478 // Add an explanation about questions in use
1479 if ($inuse) {
1480 $questionnames .= '<br />'.get_string('questionsinuse', 'quiz');
1482 $baseurl = new moodle_url('edit.php', $this->baseurl->params());
1483 $deleteurl = new moodle_url($baseurl, array('deleteselected'=>$questionlist, 'confirm'=>md5($questionlist), 'sesskey'=>sesskey()));
1485 echo $OUTPUT->confirm(get_string("deletequestionscheck", "quiz", $questionnames), $deleteurl, $baseurl);
1487 return true;
1493 * Common setup for all pages for editing questions.
1494 * @param string $baseurl the name of the script calling this funciton. For examle 'qusetion/edit.php'.
1495 * @param string $edittab code for this edit tab
1496 * @param boolean $requirecmid require cmid? default false
1497 * @param boolean $requirecourseid require courseid, if cmid is not given? default true
1498 * @return array $thispageurl, $contexts, $cmid, $cm, $module, $pagevars
1500 function question_edit_setup($edittab, $baseurl, $requirecmid = false, $requirecourseid = true) {
1501 global $DB, $PAGE;
1503 //$thispageurl is used to construct urls for all question edit pages we link to from this page. It contains an array
1504 //of parameters that are passed from page to page.
1505 // $thispageurl = new moodle_url($PAGE->url); //TODO: this looks dumb, because this method is called BEFORE $PAGE->set_page() !!!!
1506 $thispageurl = new moodle_url($baseurl);
1507 $thispageurl->remove_all_params(); // We are going to explicity add back everything important - this avoids unwanted params from being retained.
1509 if ($requirecmid){
1510 $cmid =required_param('cmid', PARAM_INT);
1511 } else {
1512 $cmid = optional_param('cmid', 0, PARAM_INT);
1514 if ($cmid){
1515 list($module, $cm) = get_module_from_cmid($cmid);
1516 $courseid = $cm->course;
1517 $thispageurl->params(compact('cmid'));
1518 require_login($courseid, false, $cm);
1519 $thiscontext = get_context_instance(CONTEXT_MODULE, $cmid);
1520 } else {
1521 $module = null;
1522 $cm = null;
1523 if ($requirecourseid){
1524 $courseid = required_param('courseid', PARAM_INT);
1525 } else {
1526 $courseid = optional_param('courseid', 0, PARAM_INT);
1528 if ($courseid){
1529 $thispageurl->params(compact('courseid'));
1530 require_login($courseid, false);
1531 $thiscontext = get_context_instance(CONTEXT_COURSE, $courseid);
1532 } else {
1533 $thiscontext = null;
1536 if (strpos($baseurl, '/question/') === 0) {
1537 navigation_node::override_active_url($thispageurl);
1540 if ($thiscontext){
1541 $contexts = new question_edit_contexts($thiscontext);
1542 $contexts->require_one_edit_tab_cap($edittab);
1544 } else {
1545 $contexts = null;
1548 $PAGE->set_pagelayout('admin');
1550 $pagevars['qpage'] = optional_param('qpage', -1, PARAM_INT);
1552 //pass 'cat' from page to page and when 'category' comes from a drop down menu
1553 //then we also reset the qpage so we go to page 1 of
1554 //a new cat.
1555 $pagevars['cat'] = optional_param('cat', 0, PARAM_SEQUENCE);// if empty will be set up later
1556 if ($category = optional_param('category', 0, PARAM_SEQUENCE)){
1557 if ($pagevars['cat'] != $category){ // is this a move to a new category?
1558 $pagevars['cat'] = $category;
1559 $pagevars['qpage'] = 0;
1562 if ($pagevars['cat']){
1563 $thispageurl->param('cat', $pagevars['cat']);
1565 if ($pagevars['qpage'] > -1) {
1566 $thispageurl->param('qpage', $pagevars['qpage']);
1567 } else {
1568 $pagevars['qpage'] = 0;
1571 $pagevars['qperpage'] = optional_param('qperpage', -1, PARAM_INT);
1572 if ($pagevars['qperpage'] > -1) {
1573 $thispageurl->param('qperpage', $pagevars['qperpage']);
1574 } else {
1575 $pagevars['qperpage'] = DEFAULT_QUESTIONS_PER_PAGE;
1578 for ($i = 1; $i <= question_bank_view::MAX_SORTS; $i++) {
1579 $param = 'qbs' . $i;
1580 if (!$sort = optional_param($param, '', PARAM_ALPHAEXT)) {
1581 break;
1583 $thispageurl->param($param, $sort);
1586 $defaultcategory = question_make_default_categories($contexts->all());
1588 $contextlistarr = array();
1589 foreach ($contexts->having_one_edit_tab_cap($edittab) as $context){
1590 $contextlistarr[] = "'$context->id'";
1592 $contextlist = join($contextlistarr, ' ,');
1593 if (!empty($pagevars['cat'])){
1594 $catparts = explode(',', $pagevars['cat']);
1595 if (!$catparts[0] || (FALSE !== array_search($catparts[1], $contextlistarr)) ||
1596 !$DB->count_records_select("question_categories", "id = ? AND contextid = ?", array($catparts[0], $catparts[1]))) {
1597 print_error('invalidcategory', 'quiz');
1599 } else {
1600 $category = $defaultcategory;
1601 $pagevars['cat'] = "$category->id,$category->contextid";
1604 if(($recurse = optional_param('recurse', -1, PARAM_BOOL)) != -1) {
1605 $pagevars['recurse'] = $recurse;
1606 $thispageurl->param('recurse', $recurse);
1607 } else {
1608 $pagevars['recurse'] = 1;
1611 if(($showhidden = optional_param('showhidden', -1, PARAM_BOOL)) != -1) {
1612 $pagevars['showhidden'] = $showhidden;
1613 $thispageurl->param('showhidden', $showhidden);
1614 } else {
1615 $pagevars['showhidden'] = 0;
1618 if(($showquestiontext = optional_param('qbshowtext', -1, PARAM_BOOL)) != -1) {
1619 $pagevars['qbshowtext'] = $showquestiontext;
1620 $thispageurl->param('qbshowtext', $showquestiontext);
1621 } else {
1622 $pagevars['qbshowtext'] = 0;
1625 //category list page
1626 $pagevars['cpage'] = optional_param('cpage', 1, PARAM_INT);
1627 if ($pagevars['cpage'] != 1){
1628 $thispageurl->param('cpage', $pagevars['cpage']);
1631 return array($thispageurl, $contexts, $cmid, $cm, $module, $pagevars);
1635 * Required for legacy reasons. Was originally global then changed to class static
1636 * as of Moodle 2.0
1638 $QUESTION_EDITTABCAPS = question_edit_contexts::$CAPS;
1641 * Make sure user is logged in as required in this context.
1643 function require_login_in_context($contextorid = null){
1644 global $DB, $CFG;
1645 if (!is_object($contextorid)){
1646 $context = get_context_instance_by_id($contextorid);
1647 } else {
1648 $context = $contextorid;
1650 if ($context && ($context->contextlevel == CONTEXT_COURSE)) {
1651 require_login($context->instanceid);
1652 } else if ($context && ($context->contextlevel == CONTEXT_MODULE)) {
1653 if ($cm = $DB->get_record('course_modules',array('id' =>$context->instanceid))) {
1654 if (!$course = $DB->get_record('course', array('id' => $cm->course))) {
1655 print_error('invalidcourseid');
1657 require_course_login($course, true, $cm);
1659 } else {
1660 print_error('invalidcoursemodule');
1662 } else if ($context && ($context->contextlevel == CONTEXT_SYSTEM)) {
1663 if (!empty($CFG->forcelogin)) {
1664 require_login();
1667 } else {
1668 require_login();
1673 * Print a form to let the user choose which question type to add.
1674 * When the form is submitted, it goes to the question.php script.
1675 * @param $hiddenparams hidden parameters to add to the form, in addition to
1676 * the qtype radio buttons.
1678 function print_choose_qtype_to_add_form($hiddenparams) {
1679 global $CFG, $QTYPES, $PAGE, $OUTPUT;
1680 $PAGE->requires->js('/question/qbank.js');
1681 echo '<div id="chooseqtypehead" class="hd">' . "\n";
1682 echo $OUTPUT->heading(get_string('chooseqtypetoadd', 'question'), 3);
1683 echo "</div>\n";
1684 echo '<div id="chooseqtype">' . "\n";
1685 echo '<form action="' . $CFG->wwwroot . '/question/question.php" method="get"><div id="qtypeformdiv">' . "\n";
1686 foreach ($hiddenparams as $name => $value) {
1687 echo '<input type="hidden" name="' . s($name) . '" value="' . s($value) . '" />' . "\n";
1689 echo "</div>\n";
1690 echo '<div class="qtypes">' . "\n";
1691 echo '<div class="instruction">' . get_string('selectaqtypefordescription', 'question') . "</div>\n";
1692 echo '<div class="realqtypes">' . "\n";
1693 $types = question_type_menu();
1694 $fakeqtypes = array();
1695 foreach ($types as $qtype => $localizedname) {
1696 if ($QTYPES[$qtype]->is_real_question_type()) {
1697 print_qtype_to_add_option($qtype, $localizedname);
1698 } else {
1699 $fakeqtypes[$qtype] = $localizedname;
1702 echo "</div>\n";
1703 echo '<div class="fakeqtypes">' . "\n";
1704 foreach ($fakeqtypes as $qtype => $localizedname) {
1705 print_qtype_to_add_option($qtype, $localizedname);
1707 echo "</div>\n";
1708 echo "</div>\n";
1709 echo '<div class="submitbuttons">' . "\n";
1710 echo '<input type="submit" value="' . get_string('next') . '" id="chooseqtype_submit" />' . "\n";
1711 echo '<input type="submit" id="chooseqtypecancel" name="addcancel" value="' . get_string('cancel') . '" />' . "\n";
1712 echo "</div></form>\n";
1713 echo "</div>\n";
1714 $PAGE->requires->js_function_call('qtype_chooser.init', array('chooseqtype'));
1718 * Private function used by the preceding one.
1719 * @param $qtype the question type.
1720 * @param $localizedname the localized name of this question type.
1722 function print_qtype_to_add_option($qtype, $localizedname) {
1723 global $QTYPES;
1724 echo '<div class="qtypeoption">' . "\n";
1725 echo '<label for="qtype_' . $qtype . '">';
1726 echo '<input type="radio" name="qtype" id="qtype_' . $qtype . '" value="' . $qtype . '" />';
1727 echo '<span class="qtypename">';
1728 $fakequestion = new stdClass;
1729 $fakequestion->qtype = $qtype;
1730 print_question_icon($fakequestion);
1731 echo $localizedname . '</span><span class="qtypesummary">' . get_string($qtype . 'summary', 'qtype_' . $qtype);
1732 echo "</span></label>\n";
1733 echo "</div>\n";
1737 * Print a button for creating a new question. This will open question/addquestion.php,
1738 * which in turn goes to question/question.php before getting back to $params['returnurl']
1739 * (by default the question bank screen).
1741 * @param integer $categoryid The id of the category that the new question should be added to.
1742 * @param array $params Other paramters to add to the URL. You need either $params['cmid'] or
1743 * $params['courseid'], and you should probably set $params['returnurl']
1744 * @param string $caption the text to display on the button.
1745 * @param string $tooltip a tooltip to add to the button (optional).
1746 * @param boolean $disabled if true, the button will be disabled.
1748 function create_new_question_button($categoryid, $params, $caption, $tooltip = '', $disabled = false) {
1749 global $CFG, $PAGE, $OUTPUT;
1750 static $choiceformprinted = false;
1751 $params['category'] = $categoryid;
1752 $url = new moodle_url('/question/addquestion.php', $params);
1753 echo $OUTPUT->single_button($url, $caption, 'get', array('disabled'=>$disabled, 'title'=>$tooltip));
1755 $PAGE->requires->yui2_lib('dragdrop');
1756 $PAGE->requires->yui2_lib('container');
1757 if (!$choiceformprinted) {
1758 echo '<div id="qtypechoicecontainer">';
1759 print_choose_qtype_to_add_form(array());
1760 echo "</div>\n";
1761 $choiceformprinted = true;