MDL-40787 Forum: Remove old commented-out code from forum
[moodle.git] / question / editlib.php
blob556dcc76763d8a63de658c9aa94e5e021e140db7
1 <?php
2 // This file is part of Moodle - http://moodle.org/
3 //
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
8 //
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
17 /**
18 * Functions used to show question editing interface
20 * @package moodlecore
21 * @subpackage questionbank
22 * @copyright 1999 onwards Martin Dougiamas and others {@link http://moodle.com}
23 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
27 defined('MOODLE_INTERNAL') || die();
29 require_once($CFG->libdir . '/questionlib.php');
31 define('DEFAULT_QUESTIONS_PER_PAGE', 20);
33 function get_module_from_cmid($cmid) {
34 global $CFG, $DB;
35 if (!$cmrec = $DB->get_record_sql("SELECT cm.*, md.name as modname
36 FROM {course_modules} cm,
37 {modules} md
38 WHERE cm.id = ? AND
39 md.id = cm.module", array($cmid))){
40 print_error('invalidcoursemodule');
41 } elseif (!$modrec =$DB->get_record($cmrec->modname, array('id' => $cmrec->instance))) {
42 print_error('invalidcoursemodule');
44 $modrec->instance = $modrec->id;
45 $modrec->cmid = $cmrec->id;
46 $cmrec->name = $modrec->name;
48 return array($modrec, $cmrec);
50 /**
51 * Function to read all questions for category into big array
53 * @param int $category category number
54 * @param bool $noparent if true only questions with NO parent will be selected
55 * @param bool $recurse include subdirectories
56 * @param bool $export set true if this is called by questionbank export
58 function get_questions_category( $category, $noparent=false, $recurse=true, $export=true ) {
59 global $DB;
61 // Build sql bit for $noparent
62 $npsql = '';
63 if ($noparent) {
64 $npsql = " and parent='0' ";
67 // Get list of categories
68 if ($recurse) {
69 $categorylist = question_categorylist($category->id);
70 } else {
71 $categorylist = array($category->id);
74 // Get the list of questions for the category
75 list($usql, $params) = $DB->get_in_or_equal($categorylist);
76 $questions = $DB->get_records_select('question', "category $usql $npsql", $params, 'qtype, name');
78 // Iterate through questions, getting stuff we need
79 $qresults = array();
80 foreach($questions as $key => $question) {
81 $question->export_process = $export;
82 $qtype = question_bank::get_qtype($question->qtype, false);
83 if ($export && $qtype->name() == 'missingtype') {
84 // Unrecognised question type. Skip this question when exporting.
85 continue;
87 $qtype->get_question_options($question);
88 $qresults[] = $question;
91 return $qresults;
94 /**
95 * @param int $categoryid a category id.
96 * @return bool whether this is the only top-level category in a context.
98 function question_is_only_toplevel_category_in_context($categoryid) {
99 global $DB;
100 return 1 == $DB->count_records_sql("
101 SELECT count(*)
102 FROM {question_categories} c1,
103 {question_categories} c2
104 WHERE c2.id = ?
105 AND c1.contextid = c2.contextid
106 AND c1.parent = 0 AND c2.parent = 0", array($categoryid));
110 * Check whether this user is allowed to delete this category.
112 * @param int $todelete a category id.
114 function question_can_delete_cat($todelete) {
115 global $DB;
116 if (question_is_only_toplevel_category_in_context($todelete)) {
117 print_error('cannotdeletecate', 'question');
118 } else {
119 $contextid = $DB->get_field('question_categories', 'contextid', array('id' => $todelete));
120 require_capability('moodle/question:managecategory', context::instance_by_id($contextid));
126 * Base class for representing a column in a {@link question_bank_view}.
128 * @copyright 2009 Tim Hunt
129 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
131 abstract class question_bank_column_base {
133 * @var question_bank_view
135 protected $qbank;
137 /** @var bool determine whether the column is td or th. */
138 protected $isheading = false;
141 * Constructor.
142 * @param $qbank the question_bank_view we are helping to render.
144 public function __construct(question_bank_view $qbank) {
145 $this->qbank = $qbank;
146 $this->init();
150 * A chance for subclasses to initialise themselves, for example to load lang strings,
151 * without having to override the constructor.
153 protected function init() {
157 * Set the column as heading
159 public function set_as_heading() {
160 $this->isheading = true;
163 public function is_extra_row() {
164 return false;
168 * Output the column header cell.
170 public function display_header() {
171 echo '<th class="header ' . $this->get_classes() . '" scope="col">';
172 $sortable = $this->is_sortable();
173 $name = $this->get_name();
174 $title = $this->get_title();
175 $tip = $this->get_title_tip();
176 if (is_array($sortable)) {
177 if ($title) {
178 echo '<div class="title">' . $title . '</div>';
180 $links = array();
181 foreach ($sortable as $subsort => $details) {
182 $links[] = $this->make_sort_link($name . '_' . $subsort,
183 $details['title'], '', !empty($details['reverse']));
185 echo '<div class="sorters">' . implode(' / ', $links) . '</div>';
186 } else if ($sortable) {
187 echo $this->make_sort_link($name, $title, $tip);
188 } else {
189 if ($tip) {
190 echo '<span title="' . $tip . '">';
192 echo $title;
193 if ($tip) {
194 echo '</span>';
197 echo "</th>\n";
201 * Title for this column. Not used if is_sortable returns an array.
202 * @param object $question the row from the $question table, augmented with extra information.
203 * @param string $rowclasses CSS class names that should be applied to this row of output.
205 protected abstract function get_title();
208 * @return string a fuller version of the name. Use this when get_title() returns
209 * something very short, and you want a longer version as a tool tip.
211 protected function get_title_tip() {
212 return '';
216 * Get a link that changes the sort order, and indicates the current sort state.
217 * @param $name internal name used for this type of sorting.
218 * @param $currentsort the current sort order -1, 0, 1 for descending, none, ascending.
219 * @param $title the link text.
220 * @param $defaultreverse whether the default sort order for this column is descending, rather than ascending.
221 * @return string HTML fragment.
223 protected function make_sort_link($sort, $title, $tip, $defaultreverse = false) {
224 $currentsort = $this->qbank->get_primary_sort_order($sort);
225 $newsortreverse = $defaultreverse;
226 if ($currentsort) {
227 $newsortreverse = $currentsort > 0;
229 if (!$tip) {
230 $tip = $title;
232 if ($newsortreverse) {
233 $tip = get_string('sortbyxreverse', '', $tip);
234 } else {
235 $tip = get_string('sortbyx', '', $tip);
237 $link = '<a href="' . $this->qbank->new_sort_url($sort, $newsortreverse) . '" title="' . $tip . '">';
238 $link .= $title;
239 if ($currentsort) {
240 $link .= $this->get_sort_icon($currentsort < 0);
242 $link .= '</a>';
243 return $link;
247 * Get an icon representing the corrent sort state.
248 * @param $reverse sort is descending, not ascending.
249 * @return string HTML image tag.
251 protected function get_sort_icon($reverse) {
252 global $OUTPUT;
253 if ($reverse) {
254 return $OUTPUT->pix_icon('t/sort_desc', get_string('desc'), '', array('class' => 'iconsort'));
255 } else {
256 return $OUTPUT->pix_icon('t/sort_asc', get_string('asc'), '', array('class' => 'iconsort'));
261 * Output this column.
262 * @param object $question the row from the $question table, augmented with extra information.
263 * @param string $rowclasses CSS class names that should be applied to this row of output.
265 public function display($question, $rowclasses) {
266 $this->display_start($question, $rowclasses);
267 $this->display_content($question, $rowclasses);
268 $this->display_end($question, $rowclasses);
272 * Output the opening column tag. If it is set as heading, it will use <th> tag instead of <td>
274 * @param stdClass $question
275 * @param array $rowclasses
277 protected function display_start($question, $rowclasses) {
278 $tag = 'td';
279 $attr = array('class' => $this->get_classes());
280 if ($this->isheading) {
281 $tag = 'th';
282 $attr['scope'] = 'row';
284 echo html_writer::start_tag($tag, $attr);
288 * @return string the CSS classes to apply to every cell in this column.
290 protected function get_classes() {
291 $classes = $this->get_extra_classes();
292 $classes[] = $this->get_name();
293 return implode(' ', $classes);
297 * @param object $question the row from the $question table, augmented with extra information.
298 * @return string internal name for this column. Used as a CSS class name,
299 * and to store information about the current sort. Must match PARAM_ALPHA.
301 public abstract function get_name();
304 * @return array any extra class names you would like applied to every cell in this column.
306 public function get_extra_classes() {
307 return array();
311 * Output the contents of this column.
312 * @param object $question the row from the $question table, augmented with extra information.
313 * @param string $rowclasses CSS class names that should be applied to this row of output.
315 protected abstract function display_content($question, $rowclasses);
318 * Output the closing column tag
320 * @param object $question
321 * @param string $rowclasses
323 protected function display_end($question, $rowclasses) {
324 $tag = 'td';
325 if ($this->isheading) {
326 $tag = 'th';
328 echo html_writer::end_tag($tag);
332 * Return an array 'table_alias' => 'JOIN clause' to bring in any data that
333 * this column required.
335 * The return values for all the columns will be checked. It is OK if two
336 * columns join in the same table with the same alias and identical JOIN clauses.
337 * If to columns try to use the same alias with different joins, you get an error.
338 * The only table included by default is the question table, which is aliased to 'q'.
340 * It is importnat that your join simply adds additional data (or NULLs) to the
341 * existing rows of the query. It must not cause additional rows.
343 * @return array 'table_alias' => 'JOIN clause'
345 public function get_extra_joins() {
346 return array();
350 * @return array fields required. use table alias 'q' for the question table, or one of the
351 * ones from get_extra_joins. Every field requested must specify a table prefix.
353 public function get_required_fields() {
354 return array();
358 * Can this column be sorted on? You can return either:
359 * + false for no (the default),
360 * + a field name, if sorting this column corresponds to sorting on that datbase field.
361 * + an array of subnames to sort on as follows
362 * return array(
363 * 'firstname' => array('field' => 'uc.firstname', 'title' => get_string('firstname')),
364 * 'lastname' => array('field' => 'uc.lastname', 'field' => get_string('lastname')),
365 * );
366 * As well as field, and field, you can also add 'revers' => 1 if you want the default sort
367 * order to be DESC.
368 * @return mixed as above.
370 public function is_sortable() {
371 return false;
375 * Helper method for building sort clauses.
376 * @param bool $reverse whether the normal direction should be reversed.
377 * @param string $normaldir 'ASC' or 'DESC'
378 * @return string 'ASC' or 'DESC'
380 protected function sortorder($reverse) {
381 if ($reverse) {
382 return ' DESC';
383 } else {
384 return ' ASC';
389 * @param $reverse Whether to sort in the reverse of the default sort order.
390 * @param $subsort if is_sortable returns an array of subnames, then this will be
391 * one of those. Otherwise will be empty.
392 * @return string some SQL to go in the order by clause.
394 public function sort_expression($reverse, $subsort) {
395 $sortable = $this->is_sortable();
396 if (is_array($sortable)) {
397 if (array_key_exists($subsort, $sortable)) {
398 return $sortable[$subsort]['field'] . $this->sortorder($reverse, !empty($sortable[$subsort]['reverse']));
399 } else {
400 throw new coding_exception('Unexpected $subsort type: ' . $subsort);
402 } else if ($sortable) {
403 return $sortable . $this->sortorder($reverse);
404 } else {
405 throw new coding_exception('sort_expression called on a non-sortable column.');
412 * A column with a checkbox for each question with name q{questionid}.
414 * @copyright 2009 Tim Hunt
415 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
417 class question_bank_checkbox_column extends question_bank_column_base {
418 protected $strselect;
419 protected $firstrow = true;
421 public function init() {
422 $this->strselect = get_string('select');
425 public function get_name() {
426 return 'checkbox';
429 protected function get_title() {
430 return '<input type="checkbox" disabled="disabled" id="qbheadercheckbox" />';
433 protected function get_title_tip() {
434 return get_string('selectquestionsforbulk', 'question');
437 protected function display_content($question, $rowclasses) {
438 global $PAGE;
439 echo '<input title="' . $this->strselect . '" type="checkbox" name="q' .
440 $question->id . '" id="checkq' . $question->id . '" value="1"/>';
441 if ($this->firstrow) {
442 $PAGE->requires->js('/question/qengine.js');
443 $module = array(
444 'name' => 'qbank',
445 'fullpath' => '/question/qbank.js',
446 'requires' => array('yui2-dom', 'yui2-event', 'yui2-container'),
447 'strings' => array(),
448 'async' => false,
450 $PAGE->requires->js_init_call('question_bank.init_checkbox_column', array(get_string('selectall'),
451 get_string('deselectall'), 'checkq' . $question->id), false, $module);
452 $this->firstrow = false;
456 public function get_required_fields() {
457 return array('q.id');
463 * A column type for the name of the question type.
465 * @copyright 2009 Tim Hunt
466 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
468 class question_bank_question_type_column extends question_bank_column_base {
469 public function get_name() {
470 return 'qtype';
473 protected function get_title() {
474 return get_string('qtypeveryshort', 'question');
477 protected function get_title_tip() {
478 return get_string('questiontype', 'question');
481 protected function display_content($question, $rowclasses) {
482 echo print_question_icon($question);
485 public function get_required_fields() {
486 return array('q.qtype');
489 public function is_sortable() {
490 return 'q.qtype';
496 * A column type for the name of the question name.
498 * @copyright 2009 Tim Hunt
499 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
501 class question_bank_question_name_column extends question_bank_column_base {
502 protected $checkboxespresent = null;
504 public function get_name() {
505 return 'questionname';
508 protected function get_title() {
509 return get_string('question');
512 protected function label_for($question) {
513 if (is_null($this->checkboxespresent)) {
514 $this->checkboxespresent = $this->qbank->has_column('checkbox');
516 if ($this->checkboxespresent) {
517 return 'checkq' . $question->id;
518 } else {
519 return '';
523 protected function display_content($question, $rowclasses) {
524 $labelfor = $this->label_for($question);
525 if ($labelfor) {
526 echo '<label for="' . $labelfor . '">';
528 echo format_string($question->name);
529 if ($labelfor) {
530 echo '</label>';
534 public function get_required_fields() {
535 return array('q.id', 'q.name');
538 public function is_sortable() {
539 return 'q.name';
545 * A column type for the name of the question creator.
547 * @copyright 2009 Tim Hunt
548 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
550 class question_bank_creator_name_column extends question_bank_column_base {
551 public function get_name() {
552 return 'creatorname';
555 protected function get_title() {
556 return get_string('createdby', 'question');
559 protected function display_content($question, $rowclasses) {
560 if (!empty($question->creatorfirstname) && !empty($question->creatorlastname)) {
561 $u = new stdClass();
562 $allnames = get_all_user_name_fields();
563 foreach ($allnames as $allname) {
564 $tempname = 'creator' . $allname;
565 if (isset($question->$tempname)) {
566 $u->$allname = $question->$tempname;
569 echo fullname($u);
573 public function get_extra_joins() {
574 return array('uc' => 'LEFT JOIN {user} uc ON uc.id = q.createdby');
577 public function get_required_fields() {
578 $allnames = get_all_user_name_fields();
579 $requiredfields = array();
580 foreach ($allnames as $allname) {
581 $requiredfields[] = 'uc.' . $allname . ' AS creator' . $allname;
583 return $requiredfields;
586 public function is_sortable() {
587 return array(
588 'firstname' => array('field' => 'uc.firstname', 'title' => get_string('firstname')),
589 'lastname' => array('field' => 'uc.lastname', 'title' => get_string('lastname')),
596 * A column type for the name of the question last modifier.
598 * @copyright 2009 Tim Hunt
599 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
601 class question_bank_modifier_name_column extends question_bank_column_base {
602 public function get_name() {
603 return 'modifiername';
606 protected function get_title() {
607 return get_string('lastmodifiedby', 'question');
610 protected function display_content($question, $rowclasses) {
611 if (!empty($question->modifierfirstname) && !empty($question->modifierlastname)) {
612 $u = new stdClass();
613 $allnames = get_all_user_name_fields();
614 foreach ($allnames as $allname) {
615 $tempname = 'modifier' . $allname;
616 if (isset($question->$tempname)) {
617 $u->$allname = $question->$tempname;
620 echo fullname($u);
624 public function get_extra_joins() {
625 return array('um' => 'LEFT JOIN {user} um ON um.id = q.modifiedby');
628 public function get_required_fields() {
629 $allnames = get_all_user_name_fields();
630 $requiredfields = array();
631 foreach ($allnames as $allname) {
632 $requiredfields[] = 'um.' . $allname . ' AS modifier' . $allname;
634 return $requiredfields;
637 public function is_sortable() {
638 return array(
639 'firstname' => array('field' => 'um.firstname', 'title' => get_string('firstname')),
640 'lastname' => array('field' => 'um.lastname', 'title' => get_string('lastname')),
647 * A base class for actions that are an icon that lets you manipulate the question in some way.
649 * @copyright 2009 Tim Hunt
650 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
652 abstract class question_bank_action_column_base extends question_bank_column_base {
654 protected function get_title() {
655 return '&#160;';
658 public function get_extra_classes() {
659 return array('iconcol');
662 protected function print_icon($icon, $title, $url) {
663 global $OUTPUT;
664 echo '<a title="' . $title . '" href="' . $url . '">
665 <img src="' . $OUTPUT->pix_url($icon) . '" class="iconsmall" alt="' . $title . '" /></a>';
668 public function get_required_fields() {
669 // createdby is required for permission checks.
670 return array('q.id', 'q.createdby');
676 * Base class for question bank columns that just contain an action icon.
678 * @copyright 2009 Tim Hunt
679 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
681 class question_bank_edit_action_column extends question_bank_action_column_base {
682 protected $stredit;
683 protected $strview;
685 public function init() {
686 parent::init();
687 $this->stredit = get_string('edit');
688 $this->strview = get_string('view');
691 public function get_name() {
692 return 'editaction';
695 protected function display_content($question, $rowclasses) {
696 if (question_has_capability_on($question, 'edit')) {
697 $this->print_icon('t/edit', $this->stredit, $this->qbank->edit_question_url($question->id));
698 } else if (question_has_capability_on($question, 'view')) {
699 $this->print_icon('i/info', $this->strview, $this->qbank->edit_question_url($question->id));
706 * Question bank columns for the preview action icon.
708 * @copyright 2009 Tim Hunt
709 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
711 class question_bank_preview_action_column extends question_bank_action_column_base {
712 protected $strpreview;
714 public function init() {
715 parent::init();
716 $this->strpreview = get_string('preview');
719 public function get_name() {
720 return 'previewaction';
723 protected function display_content($question, $rowclasses) {
724 global $OUTPUT;
725 if (question_has_capability_on($question, 'use')) {
726 // Build the icon.
727 $image = $OUTPUT->pix_icon('t/preview', $this->strpreview, '', array('class' => 'iconsmall'));
729 $link = $this->qbank->preview_question_url($question);
730 $action = new popup_action('click', $link, 'questionpreview',
731 question_preview_popup_params());
733 echo $OUTPUT->action_link($link, $image, $action, array('title' => $this->strpreview));
737 public function get_required_fields() {
738 return array('q.id');
744 * Question bank columns for the move action icon.
746 * @copyright 2009 Tim Hunt
747 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
749 class question_bank_move_action_column extends question_bank_action_column_base {
750 protected $strmove;
752 public function init() {
753 parent::init();
754 $this->strmove = get_string('move');
757 public function get_name() {
758 return 'moveaction';
761 protected function display_content($question, $rowclasses) {
762 if (question_has_capability_on($question, 'move')) {
763 $this->print_icon('t/move', $this->strmove, $this->qbank->move_question_url($question->id));
770 * action to delete (or hide) a question, or restore a previously hidden question.
772 * @copyright 2009 Tim Hunt
773 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
775 class question_bank_delete_action_column extends question_bank_action_column_base {
776 protected $strdelete;
777 protected $strrestore;
779 public function init() {
780 parent::init();
781 $this->strdelete = get_string('delete');
782 $this->strrestore = get_string('restore');
785 public function get_name() {
786 return 'deleteaction';
789 protected function display_content($question, $rowclasses) {
790 if (question_has_capability_on($question, 'edit')) {
791 if ($question->hidden) {
792 $url = new moodle_url($this->qbank->base_url(), array('unhide' => $question->id, 'sesskey'=>sesskey()));
793 $this->print_icon('t/restore', $this->strrestore, $url);
794 } else {
795 $url = new moodle_url($this->qbank->base_url(), array('deleteselected' => $question->id, 'q' . $question->id => 1, 'sesskey'=>sesskey()));
796 $this->print_icon('t/delete', $this->strdelete, $url);
801 public function get_required_fields() {
802 return array('q.id', 'q.hidden');
807 * Base class for 'columns' that are actually displayed as a row following the main question row.
809 * @copyright 2009 Tim Hunt
810 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
812 abstract class question_bank_row_base extends question_bank_column_base {
813 public function is_extra_row() {
814 return true;
817 protected function display_start($question, $rowclasses) {
818 if ($rowclasses) {
819 echo '<tr class="' . $rowclasses . '">' . "\n";
820 } else {
821 echo "<tr>\n";
823 echo '<td colspan="' . $this->qbank->get_column_count() . '" class="' . $this->get_name() . '">';
826 protected function display_end($question, $rowclasses) {
827 echo "</td></tr>\n";
832 * A column type for the name of the question name.
834 * @copyright 2009 Tim Hunt
835 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
837 class question_bank_question_text_row extends question_bank_row_base {
838 protected $formatoptions;
840 protected function init() {
841 $this->formatoptions = new stdClass();
842 $this->formatoptions->noclean = true;
843 $this->formatoptions->para = false;
846 public function get_name() {
847 return 'questiontext';
850 protected function get_title() {
851 return get_string('questiontext', 'question');
854 protected function display_content($question, $rowclasses) {
855 $text = question_rewrite_questiontext_preview_urls($question->questiontext,
856 $question->contextid, 'question', $question->id);
857 $text = format_text($text, $question->questiontextformat,
858 $this->formatoptions);
859 if ($text == '') {
860 $text = '&#160;';
862 echo $text;
865 public function get_extra_joins() {
866 return array('qc' => 'JOIN {question_categories} qc ON qc.id = q.category');
869 public function get_required_fields() {
870 return array('q.id', 'q.questiontext', 'q.questiontextformat', 'qc.contextid');
875 * This class prints a view of the question bank, including
876 * + Some controls to allow users to to select what is displayed.
877 * + A list of questions as a table.
878 * + Further controls to do things with the questions.
880 * This class gives a basic view, and provides plenty of hooks where subclasses
881 * can override parts of the display.
883 * The list of questions presented as a table is generated by creating a list of
884 * question_bank_column objects, one for each 'column' to be displayed. These
885 * manage
886 * + outputting the contents of that column, given a $question object, but also
887 * + generating the right fragments of SQL to ensure the necessary data is present,
888 * and sorted in the right order.
889 * + outputting table headers.
891 * @copyright 2009 Tim Hunt
892 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
894 class question_bank_view {
895 const MAX_SORTS = 3;
897 protected $baseurl;
898 protected $editquestionurl;
899 protected $quizorcourseid;
900 protected $contexts;
901 protected $cm;
902 protected $course;
903 protected $knowncolumntypes;
904 protected $visiblecolumns;
905 protected $extrarows;
906 protected $requiredcolumns;
907 protected $sort;
908 protected $lastchangedid;
909 protected $countsql;
910 protected $loadsql;
911 protected $sqlparams;
914 * Constructor
915 * @param question_edit_contexts $contexts
916 * @param moodle_url $pageurl
917 * @param object $course course settings
918 * @param object $cm (optional) activity settings.
920 public function __construct($contexts, $pageurl, $course, $cm = null) {
921 global $CFG, $PAGE;
923 $this->contexts = $contexts;
924 $this->baseurl = $pageurl;
925 $this->course = $course;
926 $this->cm = $cm;
928 if (!empty($cm) && $cm->modname == 'quiz') {
929 $this->quizorcourseid = '&amp;quizid=' . $cm->instance;
930 } else {
931 $this->quizorcourseid = '&amp;courseid=' .$this->course->id;
934 // Create the url of the new question page to forward to.
935 $returnurl = $pageurl->out_as_local_url(false);
936 $this->editquestionurl = new moodle_url('/question/question.php',
937 array('returnurl' => $returnurl));
938 if ($cm !== null){
939 $this->editquestionurl->param('cmid', $cm->id);
940 } else {
941 $this->editquestionurl->param('courseid', $this->course->id);
944 $this->lastchangedid = optional_param('lastchanged',0,PARAM_INT);
946 $this->init_column_types();
947 $this->init_columns($this->wanted_columns(), $this->heading_column());
948 $this->init_sort();
951 protected function wanted_columns() {
952 $columns = array('checkbox', 'qtype', 'questionname', 'editaction',
953 'previewaction', 'moveaction', 'deleteaction', 'creatorname',
954 'modifiername');
955 if (optional_param('qbshowtext', false, PARAM_BOOL)) {
956 $columns[] = 'questiontext';
958 return $columns;
962 * Specify the column heading
964 * @return string Column name for the heading
966 protected function heading_column() {
967 return 'questionname';
970 protected function known_field_types() {
971 return array(
972 new question_bank_checkbox_column($this),
973 new question_bank_question_type_column($this),
974 new question_bank_question_name_column($this),
975 new question_bank_creator_name_column($this),
976 new question_bank_modifier_name_column($this),
977 new question_bank_edit_action_column($this),
978 new question_bank_preview_action_column($this),
979 new question_bank_move_action_column($this),
980 new question_bank_delete_action_column($this),
981 new question_bank_question_text_row($this),
985 protected function init_column_types() {
986 $this->knowncolumntypes = array();
987 foreach ($this->known_field_types() as $col) {
988 $this->knowncolumntypes[$col->get_name()] = $col;
993 * Initializing table columns
995 * @param array $wanted Collection of column names
996 * @param string $heading The name of column that is set as heading
998 protected function init_columns($wanted, $heading = '') {
999 $this->visiblecolumns = array();
1000 $this->extrarows = array();
1001 foreach ($wanted as $colname) {
1002 if (!isset($this->knowncolumntypes[$colname])) {
1003 throw new coding_exception('Unknown column type ' . $colname . ' requested in init columns.');
1005 $column = $this->knowncolumntypes[$colname];
1006 if ($column->is_extra_row()) {
1007 $this->extrarows[$colname] = $column;
1008 } else {
1009 $this->visiblecolumns[$colname] = $column;
1012 $this->requiredcolumns = array_merge($this->visiblecolumns, $this->extrarows);
1013 if (array_key_exists($heading, $this->requiredcolumns)) {
1014 $this->requiredcolumns[$heading]->set_as_heading();
1019 * @param string $colname a column internal name.
1020 * @return bool is this column included in the output?
1022 public function has_column($colname) {
1023 return isset($this->visiblecolumns[$colname]);
1027 * @return int The number of columns in the table.
1029 public function get_column_count() {
1030 return count($this->visiblecolumns);
1033 public function get_courseid() {
1034 return $this->course->id;
1037 protected function init_sort() {
1038 $this->init_sort_from_params();
1039 if (empty($this->sort)) {
1040 $this->sort = $this->default_sort();
1045 * Deal with a sort name of the form columnname, or colname_subsort by
1046 * breaking it up, validating the bits that are presend, and returning them.
1047 * If there is no subsort, then $subsort is returned as ''.
1048 * @return array array($colname, $subsort).
1050 protected function parse_subsort($sort) {
1051 /// Do the parsing.
1052 if (strpos($sort, '_') !== false) {
1053 list($colname, $subsort) = explode('_', $sort, 2);
1054 } else {
1055 $colname = $sort;
1056 $subsort = '';
1058 /// Validate the column name.
1059 if (!isset($this->knowncolumntypes[$colname]) || !$this->knowncolumntypes[$colname]->is_sortable()) {
1060 for ($i = 1; $i <= question_bank_view::MAX_SORTS; $i++) {
1061 $this->baseurl->remove_params('qbs' . $i);
1063 throw new moodle_exception('unknownsortcolumn', '', $link = $this->baseurl->out(), $colname);
1065 /// Validate the subsort, if present.
1066 if ($subsort) {
1067 $subsorts = $this->knowncolumntypes[$colname]->is_sortable();
1068 if (!is_array($subsorts) || !isset($subsorts[$subsort])) {
1069 throw new moodle_exception('unknownsortcolumn', '', $link = $this->baseurl->out(), $sort);
1072 return array($colname, $subsort);
1075 protected function init_sort_from_params() {
1076 $this->sort = array();
1077 for ($i = 1; $i <= question_bank_view::MAX_SORTS; $i++) {
1078 if (!$sort = optional_param('qbs' . $i, '', PARAM_ALPHAEXT)) {
1079 break;
1081 // Work out the appropriate order.
1082 $order = 1;
1083 if ($sort[0] == '-') {
1084 $order = -1;
1085 $sort = substr($sort, 1);
1086 if (!$sort) {
1087 break;
1090 // Deal with subsorts.
1091 list($colname, $subsort) = $this->parse_subsort($sort);
1092 $this->requiredcolumns[$colname] = $this->knowncolumntypes[$colname];
1093 $this->sort[$sort] = $order;
1097 protected function sort_to_params($sorts) {
1098 $params = array();
1099 $i = 0;
1100 foreach ($sorts as $sort => $order) {
1101 $i += 1;
1102 if ($order < 0) {
1103 $sort = '-' . $sort;
1105 $params['qbs' . $i] = $sort;
1107 return $params;
1110 protected function default_sort() {
1111 $this->requiredcolumns['qtype'] = $this->knowncolumntypes['qtype'];
1112 $this->requiredcolumns['questionname'] = $this->knowncolumntypes['questionname'];
1113 return array('qtype' => 1, 'questionname' => 1);
1117 * @param $sort a column or column_subsort name.
1118 * @return int the current sort order for this column -1, 0, 1
1120 public function get_primary_sort_order($sort) {
1121 $order = reset($this->sort);
1122 $primarysort = key($this->sort);
1123 if ($sort == $primarysort) {
1124 return $order;
1125 } else {
1126 return 0;
1131 * Get a URL to redisplay the page with a new sort for the question bank.
1132 * @param string $sort the column, or column_subsort to sort on.
1133 * @param bool $newsortreverse whether to sort in reverse order.
1134 * @return string The new URL.
1136 public function new_sort_url($sort, $newsortreverse) {
1137 if ($newsortreverse) {
1138 $order = -1;
1139 } else {
1140 $order = 1;
1142 // Tricky code to add the new sort at the start, removing it from where it was before, if it was present.
1143 $newsort = array_reverse($this->sort);
1144 if (isset($newsort[$sort])) {
1145 unset($newsort[$sort]);
1147 $newsort[$sort] = $order;
1148 $newsort = array_reverse($newsort);
1149 if (count($newsort) > question_bank_view::MAX_SORTS) {
1150 $newsort = array_slice($newsort, 0, question_bank_view::MAX_SORTS, true);
1152 return $this->baseurl->out(true, $this->sort_to_params($newsort));
1155 protected function build_query_sql($category, $recurse, $showhidden) {
1156 global $DB;
1158 /// Get the required tables.
1159 $joins = array();
1160 foreach ($this->requiredcolumns as $column) {
1161 $extrajoins = $column->get_extra_joins();
1162 foreach ($extrajoins as $prefix => $join) {
1163 if (isset($joins[$prefix]) && $joins[$prefix] != $join) {
1164 throw new coding_exception('Join ' . $join . ' conflicts with previous join ' . $joins[$prefix]);
1166 $joins[$prefix] = $join;
1170 /// Get the required fields.
1171 $fields = array('q.hidden', 'q.category');
1172 foreach ($this->visiblecolumns as $column) {
1173 $fields = array_merge($fields, $column->get_required_fields());
1175 foreach ($this->extrarows as $row) {
1176 $fields = array_merge($fields, $row->get_required_fields());
1178 $fields = array_unique($fields);
1180 /// Build the order by clause.
1181 $sorts = array();
1182 foreach ($this->sort as $sort => $order) {
1183 list($colname, $subsort) = $this->parse_subsort($sort);
1184 $sorts[] = $this->requiredcolumns[$colname]->sort_expression($order < 0, $subsort);
1187 /// Build the where clause.
1188 $tests = array('q.parent = 0');
1190 if (!$showhidden) {
1191 $tests[] = 'q.hidden = 0';
1194 if ($recurse) {
1195 $categoryids = question_categorylist($category->id);
1196 } else {
1197 $categoryids = array($category->id);
1199 list($catidtest, $params) = $DB->get_in_or_equal($categoryids, SQL_PARAMS_NAMED, 'cat');
1200 $tests[] = 'q.category ' . $catidtest;
1201 $this->sqlparams = $params;
1203 /// Build the SQL.
1204 $sql = ' FROM {question} q ' . implode(' ', $joins);
1205 $sql .= ' WHERE ' . implode(' AND ', $tests);
1206 $this->countsql = 'SELECT count(1)' . $sql;
1207 $this->loadsql = 'SELECT ' . implode(', ', $fields) . $sql . ' ORDER BY ' . implode(', ', $sorts);
1208 $this->sqlparams = $params;
1211 protected function get_question_count() {
1212 global $DB;
1213 return $DB->count_records_sql($this->countsql, $this->sqlparams);
1216 protected function load_page_questions($page, $perpage) {
1217 global $DB;
1218 $questions = $DB->get_recordset_sql($this->loadsql, $this->sqlparams, $page*$perpage, $perpage);
1219 if (!$questions->valid()) {
1220 /// No questions on this page. Reset to page 0.
1221 $questions = $DB->get_recordset_sql($this->loadsql, $this->sqlparams, 0, $perpage);
1223 return $questions;
1226 public function base_url() {
1227 return $this->baseurl;
1230 public function edit_question_url($questionid) {
1231 return $this->editquestionurl->out(true, array('id' => $questionid));
1234 public function move_question_url($questionid) {
1235 return $this->editquestionurl->out(true, array('id' => $questionid, 'movecontext' => 1));
1238 public function preview_question_url($question) {
1239 return question_preview_url($question->id, null, null, null, null,
1240 $this->contexts->lowest());
1244 * Shows the question bank editing interface.
1246 * The function also processes a number of actions:
1248 * Actions affecting the question pool:
1249 * move Moves a question to a different category
1250 * deleteselected Deletes the selected questions from the category
1251 * Other actions:
1252 * category Chooses the category
1253 * displayoptions Sets display options
1255 public function display($tabname, $page, $perpage, $cat,
1256 $recurse, $showhidden, $showquestiontext) {
1257 global $PAGE, $OUTPUT;
1259 if ($this->process_actions_needing_ui()) {
1260 return;
1263 // Category selection form
1264 echo $OUTPUT->heading(get_string('questionbank', 'question'), 2);
1266 $this->display_category_form($this->contexts->having_one_edit_tab_cap($tabname),
1267 $this->baseurl, $cat);
1268 $this->display_options($recurse, $showhidden, $showquestiontext);
1270 if (!$category = $this->get_current_category($cat)) {
1271 return;
1273 $this->print_category_info($category);
1275 // continues with list of questions
1276 $this->display_question_list($this->contexts->having_one_edit_tab_cap($tabname),
1277 $this->baseurl, $cat, $this->cm,
1278 $recurse, $page, $perpage, $showhidden, $showquestiontext,
1279 $this->contexts->having_cap('moodle/question:add'));
1282 protected function print_choose_category_message($categoryandcontext) {
1283 echo "<p style=\"text-align:center;\"><b>";
1284 print_string('selectcategoryabove', 'question');
1285 echo "</b></p>";
1288 protected function get_current_category($categoryandcontext) {
1289 global $DB, $OUTPUT;
1290 list($categoryid, $contextid) = explode(',', $categoryandcontext);
1291 if (!$categoryid) {
1292 $this->print_choose_category_message($categoryandcontext);
1293 return false;
1296 if (!$category = $DB->get_record('question_categories',
1297 array('id' => $categoryid, 'contextid' => $contextid))) {
1298 echo $OUTPUT->box_start('generalbox questionbank');
1299 echo $OUTPUT->notification('Category not found!');
1300 echo $OUTPUT->box_end();
1301 return false;
1304 return $category;
1307 protected function print_category_info($category) {
1308 $formatoptions = new stdClass();
1309 $formatoptions->noclean = true;
1310 $formatoptions->overflowdiv = true;
1311 echo '<div class="boxaligncenter">';
1312 echo format_text($category->info, $category->infoformat, $formatoptions, $this->course->id);
1313 echo "</div>\n";
1317 * prints a form to choose categories
1319 protected function display_category_form($contexts, $pageurl, $current) {
1320 global $CFG, $OUTPUT;
1322 /// Get all the existing categories now
1323 echo '<div class="choosecategory">';
1324 $catmenu = question_category_options($contexts, false, 0, true);
1326 $select = new single_select($this->baseurl, 'category', $catmenu, $current, null, 'catmenu');
1327 $select->set_label(get_string('selectacategory', 'question'));
1328 echo $OUTPUT->render($select);
1329 echo "</div>\n";
1332 protected function display_options($recurse, $showhidden, $showquestiontext) {
1333 echo '<form method="get" action="edit.php" id="displayoptions">';
1334 echo "<fieldset class='invisiblefieldset'>";
1335 echo html_writer::input_hidden_params($this->baseurl, array('recurse', 'showhidden', 'qbshowtext'));
1336 $this->display_category_form_checkbox('recurse', $recurse, get_string('includesubcategories', 'question'));
1337 $this->display_category_form_checkbox('showhidden', $showhidden, get_string('showhidden', 'question'));
1338 $this->display_category_form_checkbox('qbshowtext', $showquestiontext, get_string('showquestiontext', 'question'));
1339 echo '<noscript><div class="centerpara"><input type="submit" value="'. get_string('go') .'" />';
1340 echo '</div></noscript></fieldset></form>';
1344 * Print a single option checkbox. Used by the preceeding.
1346 protected function display_category_form_checkbox($name, $value, $label) {
1347 echo '<div><input type="hidden" id="' . $name . '_off" name="' . $name . '" value="0" />';
1348 echo '<input type="checkbox" id="' . $name . '_on" name="' . $name . '" value="1"';
1349 if ($value) {
1350 echo ' checked="checked"';
1352 echo ' onchange="getElementById(\'displayoptions\').submit(); return true;" />';
1353 echo '<label for="' . $name . '_on">' . $label . '</label>';
1354 echo "</div>\n";
1357 protected function create_new_question_form($category, $canadd) {
1358 global $CFG;
1359 echo '<div class="createnewquestion">';
1360 if ($canadd) {
1361 create_new_question_button($category->id, $this->editquestionurl->params(),
1362 get_string('createnewquestion', 'question'));
1363 } else {
1364 print_string('nopermissionadd', 'question');
1366 echo '</div>';
1370 * Prints the table of questions in a category with interactions
1372 * @param object $course The course object
1373 * @param int $categoryid The id of the question category to be displayed
1374 * @param int $cm The course module record if we are in the context of a particular module, 0 otherwise
1375 * @param int $recurse This is 1 if subcategories should be included, 0 otherwise
1376 * @param int $page The number of the page to be displayed
1377 * @param int $perpage Number of questions to show per page
1378 * @param bool $showhidden True if also hidden questions should be displayed
1379 * @param bool $showquestiontext whether the text of each question should be shown in the list
1381 protected function display_question_list($contexts, $pageurl, $categoryandcontext,
1382 $cm = null, $recurse=1, $page=0, $perpage=100, $showhidden=false,
1383 $showquestiontext = false, $addcontexts = array()) {
1384 global $CFG, $DB, $OUTPUT;
1386 $category = $this->get_current_category($categoryandcontext);
1388 $cmoptions = new stdClass();
1389 $cmoptions->hasattempts = !empty($this->quizhasattempts);
1391 $strselectall = get_string('selectall');
1392 $strselectnone = get_string('deselectall');
1393 $strdelete = get_string('delete');
1395 list($categoryid, $contextid) = explode(',', $categoryandcontext);
1396 $catcontext = context::instance_by_id($contextid);
1398 $canadd = has_capability('moodle/question:add', $catcontext);
1399 $caneditall =has_capability('moodle/question:editall', $catcontext);
1400 $canuseall =has_capability('moodle/question:useall', $catcontext);
1401 $canmoveall =has_capability('moodle/question:moveall', $catcontext);
1403 $this->create_new_question_form($category, $canadd);
1405 $this->build_query_sql($category, $recurse, $showhidden);
1406 $totalnumber = $this->get_question_count();
1407 if ($totalnumber == 0) {
1408 return;
1410 $questions = $this->load_page_questions($page, $perpage);
1412 echo '<div class="categorypagingbarcontainer">';
1413 $pageing_url = new moodle_url('edit.php');
1414 $r = $pageing_url->params($pageurl->params());
1415 $pagingbar = new paging_bar($totalnumber, $page, $perpage, $pageing_url);
1416 $pagingbar->pagevar = 'qpage';
1417 echo $OUTPUT->render($pagingbar);
1418 echo '</div>';
1420 echo '<form method="post" action="edit.php">';
1421 echo '<fieldset class="invisiblefieldset" style="display: block;">';
1422 echo '<input type="hidden" name="sesskey" value="'.sesskey().'" />';
1423 echo html_writer::input_hidden_params($pageurl);
1425 echo '<div class="categoryquestionscontainer">';
1426 $this->start_table();
1427 $rowcount = 0;
1428 foreach ($questions as $question) {
1429 $this->print_table_row($question, $rowcount);
1430 $rowcount += 1;
1432 $this->end_table();
1433 echo "</div>\n";
1435 echo '<div class="categorypagingbarcontainer pagingbottom">';
1436 echo $OUTPUT->render($pagingbar);
1437 if ($totalnumber > DEFAULT_QUESTIONS_PER_PAGE) {
1438 if ($perpage == DEFAULT_QUESTIONS_PER_PAGE) {
1439 $url = new moodle_url('edit.php', array_merge($pageurl->params(), array('qperpage'=>1000)));
1440 $showall = '<a href="'.$url.'">'.get_string('showall', 'moodle', $totalnumber).'</a>';
1441 } else {
1442 $url = new moodle_url('edit.php', array_merge($pageurl->params(), array('qperpage'=>DEFAULT_QUESTIONS_PER_PAGE)));
1443 $showall = '<a href="'.$url.'">'.get_string('showperpage', 'moodle', DEFAULT_QUESTIONS_PER_PAGE).'</a>';
1445 echo "<div class='paging'>$showall</div>";
1447 echo '</div>';
1449 echo '<div class="modulespecificbuttonscontainer">';
1450 if ($caneditall || $canmoveall || $canuseall){
1451 echo '<strong>&nbsp;'.get_string('withselected', 'question').':</strong><br />';
1453 if (function_exists('module_specific_buttons')) {
1454 echo module_specific_buttons($this->cm->id,$cmoptions);
1457 // print delete and move selected question
1458 if ($caneditall) {
1459 echo '<input type="submit" name="deleteselected" value="' . $strdelete . "\" />\n";
1462 if ($canmoveall && count($addcontexts)) {
1463 echo '<input type="submit" name="move" value="'.get_string('moveto', 'question')."\" />\n";
1464 question_category_select_menu($addcontexts, false, 0, "$category->id,$category->contextid");
1467 if (function_exists('module_specific_controls') && $canuseall) {
1468 $modulespecific = module_specific_controls($totalnumber, $recurse, $category, $this->cm->id,$cmoptions);
1469 if(!empty($modulespecific)){
1470 echo "<hr />$modulespecific";
1474 echo "</div>\n";
1476 echo '</fieldset>';
1477 echo "</form>\n";
1480 protected function start_table() {
1481 echo '<table id="categoryquestions">' . "\n";
1482 echo "<thead>\n";
1483 $this->print_table_headers();
1484 echo "</thead>\n";
1485 echo "<tbody>\n";
1488 protected function end_table() {
1489 echo "</tbody>\n";
1490 echo "</table>\n";
1493 protected function print_table_headers() {
1494 echo "<tr>\n";
1495 foreach ($this->visiblecolumns as $column) {
1496 $column->display_header();
1498 echo "</tr>\n";
1501 protected function get_row_classes($question, $rowcount) {
1502 $classes = array();
1503 if ($question->hidden) {
1504 $classes[] = 'dimmed_text';
1506 if ($question->id == $this->lastchangedid) {
1507 $classes[] ='highlight';
1509 $classes[] = 'r' . ($rowcount % 2);
1510 return $classes;
1513 protected function print_table_row($question, $rowcount) {
1514 $rowclasses = implode(' ', $this->get_row_classes($question, $rowcount));
1515 if ($rowclasses) {
1516 echo '<tr class="' . $rowclasses . '">' . "\n";
1517 } else {
1518 echo "<tr>\n";
1520 foreach ($this->visiblecolumns as $column) {
1521 $column->display($question, $rowclasses);
1523 echo "</tr>\n";
1524 foreach ($this->extrarows as $row) {
1525 $row->display($question, $rowclasses);
1529 public function process_actions() {
1530 global $CFG, $DB;
1531 /// Now, check for commands on this page and modify variables as necessary
1532 if (optional_param('move', false, PARAM_BOOL) and confirm_sesskey()) {
1533 // Move selected questions to new category
1534 $category = required_param('category', PARAM_SEQUENCE);
1535 list($tocategoryid, $contextid) = explode(',', $category);
1536 if (! $tocategory = $DB->get_record('question_categories', array('id' => $tocategoryid, 'contextid' => $contextid))) {
1537 print_error('cannotfindcate', 'question');
1539 $tocontext = context::instance_by_id($contextid);
1540 require_capability('moodle/question:add', $tocontext);
1541 $rawdata = (array) data_submitted();
1542 $questionids = array();
1543 foreach ($rawdata as $key => $value) { // Parse input for question ids
1544 if (preg_match('!^q([0-9]+)$!', $key, $matches)) {
1545 $key = $matches[1];
1546 $questionids[] = $key;
1549 if ($questionids) {
1550 list($usql, $params) = $DB->get_in_or_equal($questionids);
1551 $sql = "";
1552 $questions = $DB->get_records_sql("
1553 SELECT q.*, c.contextid
1554 FROM {question} q
1555 JOIN {question_categories} c ON c.id = q.category
1556 WHERE q.id $usql", $params);
1557 foreach ($questions as $question){
1558 question_require_capability_on($question, 'move');
1560 question_move_questions_to_category($questionids, $tocategory->id);
1561 redirect($this->baseurl->out(false,
1562 array('category' => "$tocategoryid,$contextid")));
1566 if (optional_param('deleteselected', false, PARAM_BOOL)) { // delete selected questions from the category
1567 if (($confirm = optional_param('confirm', '', PARAM_ALPHANUM)) and confirm_sesskey()) { // teacher has already confirmed the action
1568 $deleteselected = required_param('deleteselected', PARAM_RAW);
1569 if ($confirm == md5($deleteselected)) {
1570 if ($questionlist = explode(',', $deleteselected)) {
1571 // for each question either hide it if it is in use or delete it
1572 foreach ($questionlist as $questionid) {
1573 $questionid = (int)$questionid;
1574 question_require_capability_on($questionid, 'edit');
1575 if (questions_in_use(array($questionid))) {
1576 $DB->set_field('question', 'hidden', 1, array('id' => $questionid));
1577 } else {
1578 question_delete_question($questionid);
1582 redirect($this->baseurl);
1583 } else {
1584 print_error('invalidconfirm', 'question');
1589 // Unhide a question
1590 if(($unhide = optional_param('unhide', '', PARAM_INT)) and confirm_sesskey()) {
1591 question_require_capability_on($unhide, 'edit');
1592 $DB->set_field('question', 'hidden', 0, array('id' => $unhide));
1594 // Purge these questions from the cache.
1595 question_bank::notify_question_edited($unhide);
1597 redirect($this->baseurl);
1601 public function process_actions_needing_ui() {
1602 global $DB, $OUTPUT;
1603 if (optional_param('deleteselected', false, PARAM_BOOL)) {
1604 // make a list of all the questions that are selected
1605 $rawquestions = $_REQUEST; // This code is called by both POST forms and GET links, so cannot use data_submitted.
1606 $questionlist = ''; // comma separated list of ids of questions to be deleted
1607 $questionnames = ''; // string with names of questions separated by <br /> with
1608 // an asterix in front of those that are in use
1609 $inuse = false; // set to true if at least one of the questions is in use
1610 foreach ($rawquestions as $key => $value) { // Parse input for question ids
1611 if (preg_match('!^q([0-9]+)$!', $key, $matches)) {
1612 $key = $matches[1];
1613 $questionlist .= $key.',';
1614 question_require_capability_on($key, 'edit');
1615 if (questions_in_use(array($key))) {
1616 $questionnames .= '* ';
1617 $inuse = true;
1619 $questionnames .= $DB->get_field('question', 'name', array('id' => $key)) . '<br />';
1622 if (!$questionlist) { // no questions were selected
1623 redirect($this->baseurl);
1625 $questionlist = rtrim($questionlist, ',');
1627 // Add an explanation about questions in use
1628 if ($inuse) {
1629 $questionnames .= '<br />'.get_string('questionsinuse', 'question');
1631 $baseurl = new moodle_url('edit.php', $this->baseurl->params());
1632 $deleteurl = new moodle_url($baseurl, array('deleteselected'=>$questionlist, 'confirm'=>md5($questionlist), 'sesskey'=>sesskey()));
1634 echo $OUTPUT->confirm(get_string('deletequestionscheck', 'question', $questionnames), $deleteurl, $baseurl);
1636 return true;
1642 * Common setup for all pages for editing questions.
1643 * @param string $baseurl the name of the script calling this funciton. For examle 'qusetion/edit.php'.
1644 * @param string $edittab code for this edit tab
1645 * @param bool $requirecmid require cmid? default false
1646 * @param bool $requirecourseid require courseid, if cmid is not given? default true
1647 * @return array $thispageurl, $contexts, $cmid, $cm, $module, $pagevars
1649 function question_edit_setup($edittab, $baseurl, $requirecmid = false, $requirecourseid = true) {
1650 global $DB, $PAGE;
1652 $thispageurl = new moodle_url($baseurl);
1653 $thispageurl->remove_all_params(); // We are going to explicity add back everything important - this avoids unwanted params from being retained.
1655 if ($requirecmid){
1656 $cmid =required_param('cmid', PARAM_INT);
1657 } else {
1658 $cmid = optional_param('cmid', 0, PARAM_INT);
1660 if ($cmid){
1661 list($module, $cm) = get_module_from_cmid($cmid);
1662 $courseid = $cm->course;
1663 $thispageurl->params(compact('cmid'));
1664 require_login($courseid, false, $cm);
1665 $thiscontext = context_module::instance($cmid);
1666 } else {
1667 $module = null;
1668 $cm = null;
1669 if ($requirecourseid){
1670 $courseid = required_param('courseid', PARAM_INT);
1671 } else {
1672 $courseid = optional_param('courseid', 0, PARAM_INT);
1674 if ($courseid){
1675 $thispageurl->params(compact('courseid'));
1676 require_login($courseid, false);
1677 $thiscontext = context_course::instance($courseid);
1678 } else {
1679 $thiscontext = null;
1683 if ($thiscontext){
1684 $contexts = new question_edit_contexts($thiscontext);
1685 $contexts->require_one_edit_tab_cap($edittab);
1687 } else {
1688 $contexts = null;
1691 $PAGE->set_pagelayout('admin');
1693 $pagevars['qpage'] = optional_param('qpage', -1, PARAM_INT);
1695 //pass 'cat' from page to page and when 'category' comes from a drop down menu
1696 //then we also reset the qpage so we go to page 1 of
1697 //a new cat.
1698 $pagevars['cat'] = optional_param('cat', 0, PARAM_SEQUENCE); // if empty will be set up later
1699 if ($category = optional_param('category', 0, PARAM_SEQUENCE)) {
1700 if ($pagevars['cat'] != $category) { // is this a move to a new category?
1701 $pagevars['cat'] = $category;
1702 $pagevars['qpage'] = 0;
1705 if ($pagevars['cat']){
1706 $thispageurl->param('cat', $pagevars['cat']);
1708 if (strpos($baseurl, '/question/') === 0) {
1709 navigation_node::override_active_url($thispageurl);
1712 if ($pagevars['qpage'] > -1) {
1713 $thispageurl->param('qpage', $pagevars['qpage']);
1714 } else {
1715 $pagevars['qpage'] = 0;
1718 $pagevars['qperpage'] = question_get_display_preference(
1719 'qperpage', DEFAULT_QUESTIONS_PER_PAGE, PARAM_INT, $thispageurl);
1721 for ($i = 1; $i <= question_bank_view::MAX_SORTS; $i++) {
1722 $param = 'qbs' . $i;
1723 if (!$sort = optional_param($param, '', PARAM_ALPHAEXT)) {
1724 break;
1726 $thispageurl->param($param, $sort);
1729 $defaultcategory = question_make_default_categories($contexts->all());
1731 $contextlistarr = array();
1732 foreach ($contexts->having_one_edit_tab_cap($edittab) as $context){
1733 $contextlistarr[] = "'$context->id'";
1735 $contextlist = join($contextlistarr, ' ,');
1736 if (!empty($pagevars['cat'])){
1737 $catparts = explode(',', $pagevars['cat']);
1738 if (!$catparts[0] || (false !== array_search($catparts[1], $contextlistarr)) ||
1739 !$DB->count_records_select("question_categories", "id = ? AND contextid = ?", array($catparts[0], $catparts[1]))) {
1740 print_error('invalidcategory', 'question');
1742 } else {
1743 $category = $defaultcategory;
1744 $pagevars['cat'] = "$category->id,$category->contextid";
1747 // Display options.
1748 $pagevars['recurse'] = question_get_display_preference('recurse', 1, PARAM_BOOL, $thispageurl);
1749 $pagevars['showhidden'] = question_get_display_preference('showhidden', 0, PARAM_BOOL, $thispageurl);
1750 $pagevars['qbshowtext'] = question_get_display_preference('qbshowtext', 0, PARAM_BOOL, $thispageurl);
1752 // Category list page.
1753 $pagevars['cpage'] = optional_param('cpage', 1, PARAM_INT);
1754 if ($pagevars['cpage'] != 1){
1755 $thispageurl->param('cpage', $pagevars['cpage']);
1758 return array($thispageurl, $contexts, $cmid, $cm, $module, $pagevars);
1762 * Get a particular question preference that is also stored as a user preference.
1763 * If the the value is given in the GET/POST request, then that value is used,
1764 * and the user preference is updated to that value. Otherwise, the last set
1765 * value of the user preference is used, or if it has never been set the default
1766 * passed to this function.
1768 * @param string $param the param name. The URL parameter set, and the GET/POST
1769 * parameter read. The user_preference name is 'question_bank_' . $param.
1770 * @param mixed $default The default value to use, if not otherwise set.
1771 * @param int $type one of the PARAM_... constants.
1772 * @param moodle_url $thispageurl if the value has been explicitly set, we add
1773 * it to this URL.
1774 * @return mixed the parameter value to use.
1776 function question_get_display_preference($param, $default, $type, $thispageurl) {
1777 $submittedvalue = optional_param($param, null, $type);
1778 if (is_null($submittedvalue)) {
1779 return get_user_preferences('question_bank_' . $param, $default);
1782 set_user_preference('question_bank_' . $param, $submittedvalue);
1783 $thispageurl->param($param, $submittedvalue);
1784 return $submittedvalue;
1788 * Make sure user is logged in as required in this context.
1790 function require_login_in_context($contextorid = null){
1791 global $DB, $CFG;
1792 if (!is_object($contextorid)){
1793 $context = context::instance_by_id($contextorid, IGNORE_MISSING);
1794 } else {
1795 $context = $contextorid;
1797 if ($context && ($context->contextlevel == CONTEXT_COURSE)) {
1798 require_login($context->instanceid);
1799 } else if ($context && ($context->contextlevel == CONTEXT_MODULE)) {
1800 if ($cm = $DB->get_record('course_modules',array('id' =>$context->instanceid))) {
1801 if (!$course = $DB->get_record('course', array('id' => $cm->course))) {
1802 print_error('invalidcourseid');
1804 require_course_login($course, true, $cm);
1806 } else {
1807 print_error('invalidcoursemodule');
1809 } else if ($context && ($context->contextlevel == CONTEXT_SYSTEM)) {
1810 if (!empty($CFG->forcelogin)) {
1811 require_login();
1814 } else {
1815 require_login();
1820 * Print a form to let the user choose which question type to add.
1821 * When the form is submitted, it goes to the question.php script.
1822 * @param $hiddenparams hidden parameters to add to the form, in addition to
1823 * the qtype radio buttons.
1824 * @param $allowedqtypes optional list of qtypes that are allowed. If given, only
1825 * those qtypes will be shown. Example value array('description', 'multichoice').
1827 function print_choose_qtype_to_add_form($hiddenparams, array $allowedqtypes = null) {
1828 global $CFG, $PAGE, $OUTPUT;
1830 echo '<div id="chooseqtypehead" class="hd">' . "\n";
1831 echo $OUTPUT->heading(get_string('chooseqtypetoadd', 'question'), 3);
1832 echo "</div>\n";
1833 echo '<div id="chooseqtype">' . "\n";
1834 echo '<form action="' . $CFG->wwwroot . '/question/question.php" method="get"><div id="qtypeformdiv">' . "\n";
1835 foreach ($hiddenparams as $name => $value) {
1836 echo '<input type="hidden" name="' . s($name) . '" value="' . s($value) . '" />' . "\n";
1838 echo "</div>\n";
1839 echo '<div class="qtypes">' . "\n";
1840 echo '<div class="instruction">' . get_string('selectaqtypefordescription', 'question') . "</div>\n";
1841 echo '<div class="realqtypes">' . "\n";
1842 $fakeqtypes = array();
1843 foreach (question_bank::get_creatable_qtypes() as $qtypename => $qtype) {
1844 if ($allowedqtypes && !in_array($qtypename, $allowedqtypes)) {
1845 continue;
1847 if ($qtype->is_real_question_type()) {
1848 print_qtype_to_add_option($qtype);
1849 } else {
1850 $fakeqtypes[] = $qtype;
1853 echo "</div>\n";
1854 echo '<div class="fakeqtypes">' . "\n";
1855 foreach ($fakeqtypes as $qtype) {
1856 print_qtype_to_add_option($qtype);
1858 echo "</div>\n";
1859 echo "</div>\n";
1860 echo '<div class="submitbuttons">' . "\n";
1861 echo '<input type="submit" value="' . get_string('next') . '" id="chooseqtype_submit" />' . "\n";
1862 echo '<input type="submit" id="chooseqtypecancel" name="addcancel" value="' . get_string('cancel') . '" />' . "\n";
1863 echo "</div></form>\n";
1864 echo "</div>\n";
1866 $PAGE->requires->js('/question/qengine.js');
1867 $module = array(
1868 'name' => 'qbank',
1869 'fullpath' => '/question/qbank.js',
1870 'requires' => array('yui2-dom', 'yui2-event', 'yui2-container'),
1871 'strings' => array(),
1872 'async' => false,
1874 $PAGE->requires->js_init_call('qtype_chooser.init', array('chooseqtype'), false, $module);
1878 * Private function used by the preceding one.
1879 * @param question_type $qtype the question type.
1881 function print_qtype_to_add_option($qtype) {
1882 echo '<div class="qtypeoption">' . "\n";
1883 echo '<label for="' . $qtype->plugin_name() . '">';
1884 echo '<input type="radio" name="qtype" id="' . $qtype->plugin_name() .
1885 '" value="' . $qtype->name() . '" />';
1886 echo '<span class="qtypename">';
1887 $fakequestion = new stdClass();
1888 $fakequestion->qtype = $qtype->name();
1889 echo print_question_icon($fakequestion);
1890 echo $qtype->menu_name() . '</span><span class="qtypesummary">' .
1891 get_string('pluginnamesummary', $qtype->plugin_name());
1892 echo "</span></label>\n";
1893 echo "</div>\n";
1897 * Print a button for creating a new question. This will open question/addquestion.php,
1898 * which in turn goes to question/question.php before getting back to $params['returnurl']
1899 * (by default the question bank screen).
1901 * @param int $categoryid The id of the category that the new question should be added to.
1902 * @param array $params Other paramters to add to the URL. You need either $params['cmid'] or
1903 * $params['courseid'], and you should probably set $params['returnurl']
1904 * @param string $caption the text to display on the button.
1905 * @param string $tooltip a tooltip to add to the button (optional).
1906 * @param bool $disabled if true, the button will be disabled.
1908 function create_new_question_button($categoryid, $params, $caption, $tooltip = '', $disabled = false) {
1909 global $CFG, $PAGE, $OUTPUT;
1910 static $choiceformprinted = false;
1911 $params['category'] = $categoryid;
1912 $url = new moodle_url('/question/addquestion.php', $params);
1913 echo $OUTPUT->single_button($url, $caption, 'get', array('disabled'=>$disabled, 'title'=>$tooltip));
1915 if (!$choiceformprinted) {
1916 echo '<div id="qtypechoicecontainer">';
1917 print_choose_qtype_to_add_form(array());
1918 echo "</div>\n";
1919 $choiceformprinted = true;