MDL-44669: mod/assign: fix batchoperations JS when using select all checkboxes.
[moodle.git] / question / editlib.php
blobf8e1be19e759cf96d8cf676aa052c4cb3ecd23bb
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 use core_question\bank\search\category_condition;
29 defined('MOODLE_INTERNAL') || die();
31 require_once($CFG->libdir . '/questionlib.php');
33 define('DEFAULT_QUESTIONS_PER_PAGE', 20);
35 function get_module_from_cmid($cmid) {
36 global $CFG, $DB;
37 if (!$cmrec = $DB->get_record_sql("SELECT cm.*, md.name as modname
38 FROM {course_modules} cm,
39 {modules} md
40 WHERE cm.id = ? AND
41 md.id = cm.module", array($cmid))){
42 print_error('invalidcoursemodule');
43 } elseif (!$modrec =$DB->get_record($cmrec->modname, array('id' => $cmrec->instance))) {
44 print_error('invalidcoursemodule');
46 $modrec->instance = $modrec->id;
47 $modrec->cmid = $cmrec->id;
48 $cmrec->name = $modrec->name;
50 return array($modrec, $cmrec);
52 /**
53 * Function to read all questions for category into big array
55 * @param int $category category number
56 * @param bool $noparent if true only questions with NO parent will be selected
57 * @param bool $recurse include subdirectories
58 * @param bool $export set true if this is called by questionbank export
60 function get_questions_category( $category, $noparent=false, $recurse=true, $export=true ) {
61 global $DB;
63 // Build sql bit for $noparent
64 $npsql = '';
65 if ($noparent) {
66 $npsql = " and parent='0' ";
69 // Get list of categories
70 if ($recurse) {
71 $categorylist = question_categorylist($category->id);
72 } else {
73 $categorylist = array($category->id);
76 // Get the list of questions for the category
77 list($usql, $params) = $DB->get_in_or_equal($categorylist);
78 $questions = $DB->get_records_select('question', "category $usql $npsql", $params, 'qtype, name');
80 // Iterate through questions, getting stuff we need
81 $qresults = array();
82 foreach($questions as $key => $question) {
83 $question->export_process = $export;
84 $qtype = question_bank::get_qtype($question->qtype, false);
85 if ($export && $qtype->name() == 'missingtype') {
86 // Unrecognised question type. Skip this question when exporting.
87 continue;
89 $qtype->get_question_options($question);
90 $qresults[] = $question;
93 return $qresults;
96 /**
97 * @param int $categoryid a category id.
98 * @return bool whether this is the only top-level category in a context.
100 function question_is_only_toplevel_category_in_context($categoryid) {
101 global $DB;
102 return 1 == $DB->count_records_sql("
103 SELECT count(*)
104 FROM {question_categories} c1,
105 {question_categories} c2
106 WHERE c2.id = ?
107 AND c1.contextid = c2.contextid
108 AND c1.parent = 0 AND c2.parent = 0", array($categoryid));
112 * Check whether this user is allowed to delete this category.
114 * @param int $todelete a category id.
116 function question_can_delete_cat($todelete) {
117 global $DB;
118 if (question_is_only_toplevel_category_in_context($todelete)) {
119 print_error('cannotdeletecate', 'question');
120 } else {
121 $contextid = $DB->get_field('question_categories', 'contextid', array('id' => $todelete));
122 require_capability('moodle/question:managecategory', context::instance_by_id($contextid));
128 * Base class for representing a column in a {@link question_bank_view}.
130 * @copyright 2009 Tim Hunt
131 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
133 abstract class question_bank_column_base {
135 * @var question_bank_view
137 protected $qbank;
139 /** @var bool determine whether the column is td or th. */
140 protected $isheading = false;
143 * Constructor.
144 * @param $qbank the question_bank_view we are helping to render.
146 public function __construct(question_bank_view $qbank) {
147 $this->qbank = $qbank;
148 $this->init();
152 * A chance for subclasses to initialise themselves, for example to load lang strings,
153 * without having to override the constructor.
155 protected function init() {
159 * Set the column as heading
161 public function set_as_heading() {
162 $this->isheading = true;
165 public function is_extra_row() {
166 return false;
170 * Output the column header cell.
172 public function display_header() {
173 echo '<th class="header ' . $this->get_classes() . '" scope="col">';
174 $sortable = $this->is_sortable();
175 $name = $this->get_name();
176 $title = $this->get_title();
177 $tip = $this->get_title_tip();
178 if (is_array($sortable)) {
179 if ($title) {
180 echo '<div class="title">' . $title . '</div>';
182 $links = array();
183 foreach ($sortable as $subsort => $details) {
184 $links[] = $this->make_sort_link($name . '_' . $subsort,
185 $details['title'], '', !empty($details['reverse']));
187 echo '<div class="sorters">' . implode(' / ', $links) . '</div>';
188 } else if ($sortable) {
189 echo $this->make_sort_link($name, $title, $tip);
190 } else {
191 if ($tip) {
192 echo '<span title="' . $tip . '">';
194 echo $title;
195 if ($tip) {
196 echo '</span>';
199 echo "</th>\n";
203 * Title for this column. Not used if is_sortable returns an array.
204 * @param object $question the row from the $question table, augmented with extra information.
205 * @param string $rowclasses CSS class names that should be applied to this row of output.
207 protected abstract function get_title();
210 * @return string a fuller version of the name. Use this when get_title() returns
211 * something very short, and you want a longer version as a tool tip.
213 protected function get_title_tip() {
214 return '';
218 * Get a link that changes the sort order, and indicates the current sort state.
219 * @param $name internal name used for this type of sorting.
220 * @param $currentsort the current sort order -1, 0, 1 for descending, none, ascending.
221 * @param $title the link text.
222 * @param $defaultreverse whether the default sort order for this column is descending, rather than ascending.
223 * @return string HTML fragment.
225 protected function make_sort_link($sort, $title, $tip, $defaultreverse = false) {
226 $currentsort = $this->qbank->get_primary_sort_order($sort);
227 $newsortreverse = $defaultreverse;
228 if ($currentsort) {
229 $newsortreverse = $currentsort > 0;
231 if (!$tip) {
232 $tip = $title;
234 if ($newsortreverse) {
235 $tip = get_string('sortbyxreverse', '', $tip);
236 } else {
237 $tip = get_string('sortbyx', '', $tip);
239 $link = '<a href="' . $this->qbank->new_sort_url($sort, $newsortreverse) . '" title="' . $tip . '">';
240 $link .= $title;
241 if ($currentsort) {
242 $link .= $this->get_sort_icon($currentsort < 0);
244 $link .= '</a>';
245 return $link;
249 * Get an icon representing the corrent sort state.
250 * @param $reverse sort is descending, not ascending.
251 * @return string HTML image tag.
253 protected function get_sort_icon($reverse) {
254 global $OUTPUT;
255 if ($reverse) {
256 return $OUTPUT->pix_icon('t/sort_desc', get_string('desc'), '', array('class' => 'iconsort'));
257 } else {
258 return $OUTPUT->pix_icon('t/sort_asc', get_string('asc'), '', array('class' => 'iconsort'));
263 * Output this column.
264 * @param object $question the row from the $question table, augmented with extra information.
265 * @param string $rowclasses CSS class names that should be applied to this row of output.
267 public function display($question, $rowclasses) {
268 $this->display_start($question, $rowclasses);
269 $this->display_content($question, $rowclasses);
270 $this->display_end($question, $rowclasses);
274 * Output the opening column tag. If it is set as heading, it will use <th> tag instead of <td>
276 * @param stdClass $question
277 * @param array $rowclasses
279 protected function display_start($question, $rowclasses) {
280 $tag = 'td';
281 $attr = array('class' => $this->get_classes());
282 if ($this->isheading) {
283 $tag = 'th';
284 $attr['scope'] = 'row';
286 echo html_writer::start_tag($tag, $attr);
290 * @return string the CSS classes to apply to every cell in this column.
292 protected function get_classes() {
293 $classes = $this->get_extra_classes();
294 $classes[] = $this->get_name();
295 return implode(' ', $classes);
299 * @param object $question the row from the $question table, augmented with extra information.
300 * @return string internal name for this column. Used as a CSS class name,
301 * and to store information about the current sort. Must match PARAM_ALPHA.
303 public abstract function get_name();
306 * @return array any extra class names you would like applied to every cell in this column.
308 public function get_extra_classes() {
309 return array();
313 * Output the contents of this column.
314 * @param object $question the row from the $question table, augmented with extra information.
315 * @param string $rowclasses CSS class names that should be applied to this row of output.
317 protected abstract function display_content($question, $rowclasses);
320 * Output the closing column tag
322 * @param object $question
323 * @param string $rowclasses
325 protected function display_end($question, $rowclasses) {
326 $tag = 'td';
327 if ($this->isheading) {
328 $tag = 'th';
330 echo html_writer::end_tag($tag);
334 * Return an array 'table_alias' => 'JOIN clause' to bring in any data that
335 * this column required.
337 * The return values for all the columns will be checked. It is OK if two
338 * columns join in the same table with the same alias and identical JOIN clauses.
339 * If to columns try to use the same alias with different joins, you get an error.
340 * The only table included by default is the question table, which is aliased to 'q'.
342 * It is importnat that your join simply adds additional data (or NULLs) to the
343 * existing rows of the query. It must not cause additional rows.
345 * @return array 'table_alias' => 'JOIN clause'
347 public function get_extra_joins() {
348 return array();
352 * @return array fields required. use table alias 'q' for the question table, or one of the
353 * ones from get_extra_joins. Every field requested must specify a table prefix.
355 public function get_required_fields() {
356 return array();
360 * Can this column be sorted on? You can return either:
361 * + false for no (the default),
362 * + a field name, if sorting this column corresponds to sorting on that datbase field.
363 * + an array of subnames to sort on as follows
364 * return array(
365 * 'firstname' => array('field' => 'uc.firstname', 'title' => get_string('firstname')),
366 * 'lastname' => array('field' => 'uc.lastname', 'field' => get_string('lastname')),
367 * );
368 * As well as field, and field, you can also add 'revers' => 1 if you want the default sort
369 * order to be DESC.
370 * @return mixed as above.
372 public function is_sortable() {
373 return false;
377 * Helper method for building sort clauses.
378 * @param bool $reverse whether the normal direction should be reversed.
379 * @param string $normaldir 'ASC' or 'DESC'
380 * @return string 'ASC' or 'DESC'
382 protected function sortorder($reverse) {
383 if ($reverse) {
384 return ' DESC';
385 } else {
386 return ' ASC';
391 * @param $reverse Whether to sort in the reverse of the default sort order.
392 * @param $subsort if is_sortable returns an array of subnames, then this will be
393 * one of those. Otherwise will be empty.
394 * @return string some SQL to go in the order by clause.
396 public function sort_expression($reverse, $subsort) {
397 $sortable = $this->is_sortable();
398 if (is_array($sortable)) {
399 if (array_key_exists($subsort, $sortable)) {
400 return $sortable[$subsort]['field'] . $this->sortorder($reverse, !empty($sortable[$subsort]['reverse']));
401 } else {
402 throw new coding_exception('Unexpected $subsort type: ' . $subsort);
404 } else if ($sortable) {
405 return $sortable . $this->sortorder($reverse);
406 } else {
407 throw new coding_exception('sort_expression called on a non-sortable column.');
414 * A column with a checkbox for each question with name q{questionid}.
416 * @copyright 2009 Tim Hunt
417 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
419 class question_bank_checkbox_column extends question_bank_column_base {
420 protected $strselect;
421 protected $firstrow = true;
423 public function init() {
424 $this->strselect = get_string('select');
427 public function get_name() {
428 return 'checkbox';
431 protected function get_title() {
432 return '<input type="checkbox" disabled="disabled" id="qbheadercheckbox" />';
435 protected function get_title_tip() {
436 return get_string('selectquestionsforbulk', 'question');
439 protected function display_content($question, $rowclasses) {
440 global $PAGE;
441 echo '<input title="' . $this->strselect . '" type="checkbox" name="q' .
442 $question->id . '" id="checkq' . $question->id . '" value="1"/>';
443 if ($this->firstrow) {
444 $PAGE->requires->js('/question/qengine.js');
445 $module = array(
446 'name' => 'qbank',
447 'fullpath' => '/question/qbank.js',
448 'requires' => array('yui2-dom', 'yui2-event', 'yui2-container'),
449 'strings' => array(),
450 'async' => false,
452 $PAGE->requires->js_init_call('question_bank.init_checkbox_column', array(get_string('selectall'),
453 get_string('deselectall'), 'checkq' . $question->id), false, $module);
454 $this->firstrow = false;
458 public function get_required_fields() {
459 return array('q.id');
465 * A column type for the name of the question type.
467 * @copyright 2009 Tim Hunt
468 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
470 class question_bank_question_type_column extends question_bank_column_base {
471 public function get_name() {
472 return 'qtype';
475 protected function get_title() {
476 return get_string('qtypeveryshort', 'question');
479 protected function get_title_tip() {
480 return get_string('questiontype', 'question');
483 protected function display_content($question, $rowclasses) {
484 echo print_question_icon($question);
487 public function get_required_fields() {
488 return array('q.qtype');
491 public function is_sortable() {
492 return 'q.qtype';
498 * A column type for the name of the question name.
500 * @copyright 2009 Tim Hunt
501 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
503 class question_bank_question_name_column extends question_bank_column_base {
504 protected $checkboxespresent = null;
506 public function get_name() {
507 return 'questionname';
510 protected function get_title() {
511 return get_string('question');
514 protected function label_for($question) {
515 if (is_null($this->checkboxespresent)) {
516 $this->checkboxespresent = $this->qbank->has_column('checkbox');
518 if ($this->checkboxespresent) {
519 return 'checkq' . $question->id;
520 } else {
521 return '';
525 protected function display_content($question, $rowclasses) {
526 $labelfor = $this->label_for($question);
527 if ($labelfor) {
528 echo '<label for="' . $labelfor . '">';
530 echo format_string($question->name);
531 if ($labelfor) {
532 echo '</label>';
536 public function get_required_fields() {
537 return array('q.id', 'q.name');
540 public function is_sortable() {
541 return 'q.name';
547 * A column type for the name of the question creator.
549 * @copyright 2009 Tim Hunt
550 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
552 class question_bank_creator_name_column extends question_bank_column_base {
553 public function get_name() {
554 return 'creatorname';
557 protected function get_title() {
558 return get_string('createdby', 'question');
561 protected function display_content($question, $rowclasses) {
562 if (!empty($question->creatorfirstname) && !empty($question->creatorlastname)) {
563 $u = new stdClass();
564 $u = username_load_fields_from_object($u, $question, 'creator');
565 echo fullname($u);
569 public function get_extra_joins() {
570 return array('uc' => 'LEFT JOIN {user} uc ON uc.id = q.createdby');
573 public function get_required_fields() {
574 $allnames = get_all_user_name_fields();
575 $requiredfields = array();
576 foreach ($allnames as $allname) {
577 $requiredfields[] = 'uc.' . $allname . ' AS creator' . $allname;
579 return $requiredfields;
582 public function is_sortable() {
583 return array(
584 'firstname' => array('field' => 'uc.firstname', 'title' => get_string('firstname')),
585 'lastname' => array('field' => 'uc.lastname', 'title' => get_string('lastname')),
592 * A column type for the name of the question last modifier.
594 * @copyright 2009 Tim Hunt
595 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
597 class question_bank_modifier_name_column extends question_bank_column_base {
598 public function get_name() {
599 return 'modifiername';
602 protected function get_title() {
603 return get_string('lastmodifiedby', 'question');
606 protected function display_content($question, $rowclasses) {
607 if (!empty($question->modifierfirstname) && !empty($question->modifierlastname)) {
608 $u = new stdClass();
609 $u = username_load_fields_from_object($u, $question, 'modifier');
610 echo fullname($u);
614 public function get_extra_joins() {
615 return array('um' => 'LEFT JOIN {user} um ON um.id = q.modifiedby');
618 public function get_required_fields() {
619 $allnames = get_all_user_name_fields();
620 $requiredfields = array();
621 foreach ($allnames as $allname) {
622 $requiredfields[] = 'um.' . $allname . ' AS modifier' . $allname;
624 return $requiredfields;
627 public function is_sortable() {
628 return array(
629 'firstname' => array('field' => 'um.firstname', 'title' => get_string('firstname')),
630 'lastname' => array('field' => 'um.lastname', 'title' => get_string('lastname')),
637 * A base class for actions that are an icon that lets you manipulate the question in some way.
639 * @copyright 2009 Tim Hunt
640 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
642 abstract class question_bank_action_column_base extends question_bank_column_base {
644 protected function get_title() {
645 return '&#160;';
648 public function get_extra_classes() {
649 return array('iconcol');
652 protected function print_icon($icon, $title, $url) {
653 global $OUTPUT;
654 echo '<a title="' . $title . '" href="' . $url . '">
655 <img src="' . $OUTPUT->pix_url($icon) . '" class="iconsmall" alt="' . $title . '" /></a>';
658 public function get_required_fields() {
659 // createdby is required for permission checks.
660 return array('q.id', 'q.createdby');
666 * Base class for question bank columns that just contain an action icon.
668 * @copyright 2009 Tim Hunt
669 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
671 class question_bank_edit_action_column extends question_bank_action_column_base {
672 protected $stredit;
673 protected $strview;
675 public function init() {
676 parent::init();
677 $this->stredit = get_string('edit');
678 $this->strview = get_string('view');
681 public function get_name() {
682 return 'editaction';
685 protected function display_content($question, $rowclasses) {
686 if (question_has_capability_on($question, 'edit')) {
687 $this->print_icon('t/edit', $this->stredit, $this->qbank->edit_question_url($question->id));
688 } else if (question_has_capability_on($question, 'view')) {
689 $this->print_icon('i/info', $this->strview, $this->qbank->edit_question_url($question->id));
695 * Question bank column for the duplicate action icon.
697 * @copyright 2013 The Open University
698 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
700 class question_bank_copy_action_column extends question_bank_action_column_base {
701 /** @var string avoids repeated calls to get_string('duplicate'). */
702 protected $strcopy;
704 public function init() {
705 parent::init();
706 $this->strcopy = get_string('duplicate');
709 public function get_name() {
710 return 'copyaction';
713 protected function display_content($question, $rowclasses) {
714 // To copy a question, you need permission to add a question in the same
715 // category as the existing question, and ability to access the details of
716 // the question being copied.
717 if (question_has_capability_on($question, 'add') &&
718 (question_has_capability_on($question, 'edit') || question_has_capability_on($question, 'view'))) {
719 $this->print_icon('t/copy', $this->strcopy, $this->qbank->copy_question_url($question->id));
725 * Question bank columns for the preview action icon.
727 * @copyright 2009 Tim Hunt
728 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
730 class question_bank_preview_action_column extends question_bank_action_column_base {
731 public function init() {
732 parent::init();
735 public function get_name() {
736 return 'previewaction';
739 protected function display_content($question, $rowclasses) {
740 global $PAGE;
741 if (question_has_capability_on($question, 'use')) {
742 echo $PAGE->get_renderer('core_question')->question_preview_link(
743 $question->id, $this->qbank->get_most_specific_context(), false);
747 public function get_required_fields() {
748 return array('q.id');
754 * action to delete (or hide) a question, or restore a previously hidden question.
756 * @copyright 2009 Tim Hunt
757 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
759 class question_bank_delete_action_column extends question_bank_action_column_base {
760 protected $strdelete;
761 protected $strrestore;
763 public function init() {
764 parent::init();
765 $this->strdelete = get_string('delete');
766 $this->strrestore = get_string('restore');
769 public function get_name() {
770 return 'deleteaction';
773 protected function display_content($question, $rowclasses) {
774 if (question_has_capability_on($question, 'edit')) {
775 if ($question->hidden) {
776 $url = new moodle_url($this->qbank->base_url(), array('unhide' => $question->id, 'sesskey'=>sesskey()));
777 $this->print_icon('t/restore', $this->strrestore, $url);
778 } else {
779 $url = new moodle_url($this->qbank->base_url(), array('deleteselected' => $question->id, 'q' . $question->id => 1, 'sesskey'=>sesskey()));
780 $this->print_icon('t/delete', $this->strdelete, $url);
785 public function get_required_fields() {
786 return array('q.id', 'q.hidden');
791 * Base class for 'columns' that are actually displayed as a row following the main question row.
793 * @copyright 2009 Tim Hunt
794 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
796 abstract class question_bank_row_base extends question_bank_column_base {
797 public function is_extra_row() {
798 return true;
801 protected function display_start($question, $rowclasses) {
802 if ($rowclasses) {
803 echo '<tr class="' . $rowclasses . '">' . "\n";
804 } else {
805 echo "<tr>\n";
807 echo '<td colspan="' . $this->qbank->get_column_count() . '" class="' . $this->get_name() . '">';
810 protected function display_end($question, $rowclasses) {
811 echo "</td></tr>\n";
816 * A column type for the name of the question name.
818 * @copyright 2009 Tim Hunt
819 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
821 class question_bank_question_text_row extends question_bank_row_base {
822 protected $formatoptions;
824 protected function init() {
825 $this->formatoptions = new stdClass();
826 $this->formatoptions->noclean = true;
827 $this->formatoptions->para = false;
830 public function get_name() {
831 return 'questiontext';
834 protected function get_title() {
835 return get_string('questiontext', 'question');
838 protected function display_content($question, $rowclasses) {
839 $text = question_rewrite_question_preview_urls($question->questiontext, $question->id,
840 $question->contextid, 'question', 'questiontext', $question->id,
841 $question->contextid, 'core_question');
842 $text = format_text($text, $question->questiontextformat,
843 $this->formatoptions);
844 if ($text == '') {
845 $text = '&#160;';
847 echo $text;
850 public function get_extra_joins() {
851 return array('qc' => 'JOIN {question_categories} qc ON qc.id = q.category');
854 public function get_required_fields() {
855 return array('q.id', 'q.questiontext', 'q.questiontextformat', 'qc.contextid');
860 * This class prints a view of the question bank, including
861 * + Some controls to allow users to to select what is displayed.
862 * + A list of questions as a table.
863 * + Further controls to do things with the questions.
865 * This class gives a basic view, and provides plenty of hooks where subclasses
866 * can override parts of the display.
868 * The list of questions presented as a table is generated by creating a list of
869 * question_bank_column objects, one for each 'column' to be displayed. These
870 * manage
871 * + outputting the contents of that column, given a $question object, but also
872 * + generating the right fragments of SQL to ensure the necessary data is present,
873 * and sorted in the right order.
874 * + outputting table headers.
876 * @copyright 2009 Tim Hunt
877 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
879 class question_bank_view {
880 const MAX_SORTS = 3;
882 protected $baseurl;
883 protected $editquestionurl;
884 protected $quizorcourseid;
885 protected $contexts;
886 protected $cm;
887 protected $course;
888 protected $knowncolumntypes;
889 protected $visiblecolumns;
890 protected $extrarows;
891 protected $requiredcolumns;
892 protected $sort;
893 protected $lastchangedid;
894 protected $countsql;
895 protected $loadsql;
896 protected $sqlparams;
897 /** @var array of \core_question\bank\search\condition objects. */
898 protected $searchconditions = array();
901 * Constructor
902 * @param question_edit_contexts $contexts
903 * @param moodle_url $pageurl
904 * @param object $course course settings
905 * @param object $cm (optional) activity settings.
907 public function __construct($contexts, $pageurl, $course, $cm = null) {
908 global $CFG, $PAGE;
910 $this->contexts = $contexts;
911 $this->baseurl = $pageurl;
912 $this->course = $course;
913 $this->cm = $cm;
915 if (!empty($cm) && $cm->modname == 'quiz') {
916 $this->quizorcourseid = '&amp;quizid=' . $cm->instance;
917 } else {
918 $this->quizorcourseid = '&amp;courseid=' .$this->course->id;
921 // Create the url of the new question page to forward to.
922 $returnurl = $pageurl->out_as_local_url(false);
923 $this->editquestionurl = new moodle_url('/question/question.php',
924 array('returnurl' => $returnurl));
925 if ($cm !== null){
926 $this->editquestionurl->param('cmid', $cm->id);
927 } else {
928 $this->editquestionurl->param('courseid', $this->course->id);
931 $this->lastchangedid = optional_param('lastchanged',0,PARAM_INT);
933 $this->init_column_types();
934 $this->init_columns($this->wanted_columns(), $this->heading_column());
935 $this->init_sort();
936 $this->init_search_conditions($this->contexts, $this->course, $this->cm);
940 * Initialize search conditions from plugins
941 * local_*_get_question_bank_search_conditions() must return an array of
942 * \core_question\bank\search\condition objects.
944 protected function init_search_conditions() {
945 $searchplugins = get_plugin_list_with_function('local', 'get_question_bank_search_conditions');
946 foreach ($searchplugins as $component => $function) {
947 foreach ($function($this) as $searchobject) {
948 $this->add_searchcondition($searchobject);
953 protected function wanted_columns() {
954 $columns = array('checkbox', 'qtype', 'questionname', 'editaction', 'copyaction',
955 'previewaction', 'deleteaction', 'creatorname', 'modifiername');
956 if (question_get_display_preference('qbshowtext', 0, PARAM_BOOL, new moodle_url(''))) {
957 $columns[] = 'questiontext';
959 return $columns;
963 * Specify the column heading
965 * @return string Column name for the heading
967 protected function heading_column() {
968 return 'questionname';
971 protected function known_field_types() {
972 return array(
973 new question_bank_checkbox_column($this),
974 new question_bank_question_type_column($this),
975 new question_bank_question_name_column($this),
976 new question_bank_creator_name_column($this),
977 new question_bank_modifier_name_column($this),
978 new question_bank_edit_action_column($this),
979 new question_bank_copy_action_column($this),
980 new question_bank_preview_action_column($this),
981 new question_bank_delete_action_column($this),
982 new question_bank_question_text_row($this),
986 protected function init_column_types() {
987 $this->knowncolumntypes = array();
988 foreach ($this->known_field_types() as $col) {
989 $this->knowncolumntypes[$col->get_name()] = $col;
994 * Initializing table columns
996 * @param array $wanted Collection of column names
997 * @param string $heading The name of column that is set as heading
999 protected function init_columns($wanted, $heading = '') {
1000 $this->visiblecolumns = array();
1001 $this->extrarows = array();
1002 foreach ($wanted as $colname) {
1003 if (!isset($this->knowncolumntypes[$colname])) {
1004 throw new coding_exception('Unknown column type ' . $colname . ' requested in init columns.');
1006 $column = $this->knowncolumntypes[$colname];
1007 if ($column->is_extra_row()) {
1008 $this->extrarows[$colname] = $column;
1009 } else {
1010 $this->visiblecolumns[$colname] = $column;
1013 $this->requiredcolumns = array_merge($this->visiblecolumns, $this->extrarows);
1014 if (array_key_exists($heading, $this->requiredcolumns)) {
1015 $this->requiredcolumns[$heading]->set_as_heading();
1020 * @param string $colname a column internal name.
1021 * @return bool is this column included in the output?
1023 public function has_column($colname) {
1024 return isset($this->visiblecolumns[$colname]);
1028 * @return int The number of columns in the table.
1030 public function get_column_count() {
1031 return count($this->visiblecolumns);
1034 public function get_courseid() {
1035 return $this->course->id;
1038 protected function init_sort() {
1039 $this->init_sort_from_params();
1040 if (empty($this->sort)) {
1041 $this->sort = $this->default_sort();
1046 * Deal with a sort name of the form columnname, or colname_subsort by
1047 * breaking it up, validating the bits that are presend, and returning them.
1048 * If there is no subsort, then $subsort is returned as ''.
1049 * @return array array($colname, $subsort).
1051 protected function parse_subsort($sort) {
1052 /// Do the parsing.
1053 if (strpos($sort, '_') !== false) {
1054 list($colname, $subsort) = explode('_', $sort, 2);
1055 } else {
1056 $colname = $sort;
1057 $subsort = '';
1059 /// Validate the column name.
1060 if (!isset($this->knowncolumntypes[$colname]) || !$this->knowncolumntypes[$colname]->is_sortable()) {
1061 for ($i = 1; $i <= question_bank_view::MAX_SORTS; $i++) {
1062 $this->baseurl->remove_params('qbs' . $i);
1064 throw new moodle_exception('unknownsortcolumn', '', $link = $this->baseurl->out(), $colname);
1066 /// Validate the subsort, if present.
1067 if ($subsort) {
1068 $subsorts = $this->knowncolumntypes[$colname]->is_sortable();
1069 if (!is_array($subsorts) || !isset($subsorts[$subsort])) {
1070 throw new moodle_exception('unknownsortcolumn', '', $link = $this->baseurl->out(), $sort);
1073 return array($colname, $subsort);
1076 protected function init_sort_from_params() {
1077 $this->sort = array();
1078 for ($i = 1; $i <= question_bank_view::MAX_SORTS; $i++) {
1079 if (!$sort = optional_param('qbs' . $i, '', PARAM_ALPHAEXT)) {
1080 break;
1082 // Work out the appropriate order.
1083 $order = 1;
1084 if ($sort[0] == '-') {
1085 $order = -1;
1086 $sort = substr($sort, 1);
1087 if (!$sort) {
1088 break;
1091 // Deal with subsorts.
1092 list($colname, $subsort) = $this->parse_subsort($sort);
1093 $this->requiredcolumns[$colname] = $this->knowncolumntypes[$colname];
1094 $this->sort[$sort] = $order;
1098 protected function sort_to_params($sorts) {
1099 $params = array();
1100 $i = 0;
1101 foreach ($sorts as $sort => $order) {
1102 $i += 1;
1103 if ($order < 0) {
1104 $sort = '-' . $sort;
1106 $params['qbs' . $i] = $sort;
1108 return $params;
1111 protected function default_sort() {
1112 $this->requiredcolumns['qtype'] = $this->knowncolumntypes['qtype'];
1113 $this->requiredcolumns['questionname'] = $this->knowncolumntypes['questionname'];
1114 return array('qtype' => 1, 'questionname' => 1);
1118 * @param $sort a column or column_subsort name.
1119 * @return int the current sort order for this column -1, 0, 1
1121 public function get_primary_sort_order($sort) {
1122 $order = reset($this->sort);
1123 $primarysort = key($this->sort);
1124 if ($sort == $primarysort) {
1125 return $order;
1126 } else {
1127 return 0;
1132 * Get a URL to redisplay the page with a new sort for the question bank.
1133 * @param string $sort the column, or column_subsort to sort on.
1134 * @param bool $newsortreverse whether to sort in reverse order.
1135 * @return string The new URL.
1137 public function new_sort_url($sort, $newsortreverse) {
1138 if ($newsortreverse) {
1139 $order = -1;
1140 } else {
1141 $order = 1;
1143 // Tricky code to add the new sort at the start, removing it from where it was before, if it was present.
1144 $newsort = array_reverse($this->sort);
1145 if (isset($newsort[$sort])) {
1146 unset($newsort[$sort]);
1148 $newsort[$sort] = $order;
1149 $newsort = array_reverse($newsort);
1150 if (count($newsort) > question_bank_view::MAX_SORTS) {
1151 $newsort = array_slice($newsort, 0, question_bank_view::MAX_SORTS, true);
1153 return $this->baseurl->out(true, $this->sort_to_params($newsort));
1157 * Create the SQL query to retrieve the indicated questions
1158 * @param stdClass $category no longer used.
1159 * @param bool $recurse no longer used.
1160 * @param bool $showhidden no longer used.
1161 * @deprecated since Moodle 2.7 MDL-40313.
1162 * @see build_query()
1163 * @see \core_question\bank\search\condition
1164 * @todo MDL-41978 This will be deleted in Moodle 2.8
1166 protected function build_query_sql($category, $recurse, $showhidden) {
1167 debugging('build_query_sql() is deprecated, please use question_bank_view::build_query() and ' .
1168 '\core_question\bank\search\condition classes instead.', DEBUG_DEVELOPER);
1169 self::build_query();
1173 * Create the SQL query to retrieve the indicated questions, based on
1174 * \core_question\bank\search\condition filters.
1176 protected function build_query() {
1177 global $DB;
1179 /// Get the required tables.
1180 $joins = array();
1181 foreach ($this->requiredcolumns as $column) {
1182 $extrajoins = $column->get_extra_joins();
1183 foreach ($extrajoins as $prefix => $join) {
1184 if (isset($joins[$prefix]) && $joins[$prefix] != $join) {
1185 throw new coding_exception('Join ' . $join . ' conflicts with previous join ' . $joins[$prefix]);
1187 $joins[$prefix] = $join;
1191 /// Get the required fields.
1192 $fields = array('q.hidden', 'q.category');
1193 foreach ($this->visiblecolumns as $column) {
1194 $fields = array_merge($fields, $column->get_required_fields());
1196 foreach ($this->extrarows as $row) {
1197 $fields = array_merge($fields, $row->get_required_fields());
1199 $fields = array_unique($fields);
1201 /// Build the order by clause.
1202 $sorts = array();
1203 foreach ($this->sort as $sort => $order) {
1204 list($colname, $subsort) = $this->parse_subsort($sort);
1205 $sorts[] = $this->requiredcolumns[$colname]->sort_expression($order < 0, $subsort);
1208 /// Build the where clause.
1209 $tests = array('q.parent = 0');
1210 $this->sqlparams = array();
1211 foreach ($this->searchconditions as $searchcondition) {
1212 if ($searchcondition->where()) {
1213 $tests[] = '((' . $searchcondition->where() .'))';
1215 if ($searchcondition->params()) {
1216 $this->sqlparams = array_merge($this->sqlparams, $searchcondition->params());
1219 /// Build the SQL.
1220 $sql = ' FROM {question} q ' . implode(' ', $joins);
1221 $sql .= ' WHERE ' . implode(' AND ', $tests);
1222 $this->countsql = 'SELECT count(1)' . $sql;
1223 $this->loadsql = 'SELECT ' . implode(', ', $fields) . $sql . ' ORDER BY ' . implode(', ', $sorts);
1226 protected function get_question_count() {
1227 global $DB;
1228 return $DB->count_records_sql($this->countsql, $this->sqlparams);
1231 protected function load_page_questions($page, $perpage) {
1232 global $DB;
1233 $questions = $DB->get_recordset_sql($this->loadsql, $this->sqlparams, $page*$perpage, $perpage);
1234 if (!$questions->valid()) {
1235 /// No questions on this page. Reset to page 0.
1236 $questions = $DB->get_recordset_sql($this->loadsql, $this->sqlparams, 0, $perpage);
1238 return $questions;
1241 public function base_url() {
1242 return $this->baseurl;
1245 public function edit_question_url($questionid) {
1246 return $this->editquestionurl->out(true, array('id' => $questionid));
1250 * Get the URL for duplicating a given question.
1251 * @param int $questionid the question id.
1252 * @return moodle_url the URL.
1254 public function copy_question_url($questionid) {
1255 return $this->editquestionurl->out(true, array('id' => $questionid, 'makecopy' => 1));
1259 * Get the context we are displaying the question bank for.
1260 * @return context context object.
1262 public function get_most_specific_context() {
1263 return $this->contexts->lowest();
1267 * Get the URL to preview a question.
1268 * @param stdClass $questiondata the data defining the question.
1269 * @return moodle_url the URL.
1271 public function preview_question_url($questiondata) {
1272 return question_preview_url($questiondata->id, null, null, null, null,
1273 $this->get_most_specific_context());
1277 * Shows the question bank editing interface.
1279 * The function also processes a number of actions:
1281 * Actions affecting the question pool:
1282 * move Moves a question to a different category
1283 * deleteselected Deletes the selected questions from the category
1284 * Other actions:
1285 * category Chooses the category
1286 * displayoptions Sets display options
1288 public function display($tabname, $page, $perpage, $cat,
1289 $recurse, $showhidden, $showquestiontext) {
1290 global $PAGE, $OUTPUT;
1292 if ($this->process_actions_needing_ui()) {
1293 return;
1295 $editcontexts = $this->contexts->having_one_edit_tab_cap($tabname);
1296 // Category selection form
1297 echo $OUTPUT->heading(get_string('questionbank', 'question'), 2);
1298 array_unshift($this->searchconditions, new \core_question\bank\search\hidden_condition(!$showhidden));
1299 array_unshift($this->searchconditions, new \core_question\bank\search\category_condition(
1300 $cat, $recurse, $editcontexts, $this->baseurl, $this->course));
1301 $this->display_options_form($showquestiontext);
1303 // continues with list of questions
1304 $this->display_question_list($this->contexts->having_one_edit_tab_cap($tabname),
1305 $this->baseurl, $cat, $this->cm,
1306 null, $page, $perpage, $showhidden, $showquestiontext,
1307 $this->contexts->having_cap('moodle/question:add'));
1310 protected function print_choose_category_message($categoryandcontext) {
1311 echo "<p style=\"text-align:center;\"><b>";
1312 print_string('selectcategoryabove', 'question');
1313 echo "</b></p>";
1316 protected function get_current_category($categoryandcontext) {
1317 global $DB, $OUTPUT;
1318 list($categoryid, $contextid) = explode(',', $categoryandcontext);
1319 if (!$categoryid) {
1320 $this->print_choose_category_message($categoryandcontext);
1321 return false;
1324 if (!$category = $DB->get_record('question_categories',
1325 array('id' => $categoryid, 'contextid' => $contextid))) {
1326 echo $OUTPUT->box_start('generalbox questionbank');
1327 echo $OUTPUT->notification('Category not found!');
1328 echo $OUTPUT->box_end();
1329 return false;
1332 return $category;
1336 * prints category information
1337 * @param stdClass $category the category row from the database.
1338 * @deprecated since Moodle 2.7 MDL-40313.
1339 * @see \core_question\bank\search\condition
1340 * @todo MDL-41978 This will be deleted in Moodle 2.8
1342 protected function print_category_info($category) {
1343 $formatoptions = new stdClass();
1344 $formatoptions->noclean = true;
1345 $formatoptions->overflowdiv = true;
1346 echo '<div class="boxaligncenter">';
1347 echo format_text($category->info, $category->infoformat, $formatoptions, $this->course->id);
1348 echo "</div>\n";
1352 * Prints a form to choose categories
1353 * @deprecated since Moodle 2.7 MDL-40313.
1354 * @see \core_question\bank\search\condition
1355 * @todo MDL-41978 This will be deleted in Moodle 2.8
1357 protected function display_category_form($contexts, $pageurl, $current) {
1358 global $OUTPUT;
1360 debugging('display_category_form() is deprecated, please use ' .
1361 '\core_question\bank\search\condition instead.', DEBUG_DEVELOPER);
1362 /// Get all the existing categories now
1363 echo '<div class="choosecategory">';
1364 $catmenu = question_category_options($contexts, false, 0, true);
1366 $select = new single_select($this->baseurl, 'category', $catmenu, $current, null, 'catmenu');
1367 $select->set_label(get_string('selectacategory', 'question'));
1368 echo $OUTPUT->render($select);
1369 echo "</div>\n";
1373 * Display the options form.
1374 * @param bool $recurse no longer used.
1375 * @param bool $showhidden no longer used.
1376 * @param bool $showquestiontext whether to show the question text.
1377 * @deprecated since Moodle 2.7 MDL-40313.
1378 * @see display_options_form
1379 * @todo MDL-41978 This will be deleted in Moodle 2.8
1380 * @see \core_question\bank\search\condition
1382 protected function display_options($recurse, $showhidden, $showquestiontext) {
1383 debugging('display_options() is deprecated, please use display_options_form instead.', DEBUG_DEVELOPER);
1384 return $this->display_options_form($showquestiontext);
1388 * Print a single option checkbox.
1389 * @deprecated since Moodle 2.7 MDL-40313.
1390 * @see \core_question\bank\search\condition
1391 * @see html_writer::checkbox
1392 * @todo MDL-41978 This will be deleted in Moodle 2.8
1394 protected function display_category_form_checkbox($name, $value, $label) {
1395 debugging('display_category_form_checkbox() is deprecated, ' .
1396 'please use \core_question\bank\search\condition instead.', DEBUG_DEVELOPER);
1397 echo '<div><input type="hidden" id="' . $name . '_off" name="' . $name . '" value="0" />';
1398 echo '<input type="checkbox" id="' . $name . '_on" name="' . $name . '" value="1"';
1399 if ($value) {
1400 echo ' checked="checked"';
1402 echo ' onchange="getElementById(\'displayoptions\').submit(); return true;" />';
1403 echo '<label for="' . $name . '_on">' . $label . '</label>';
1404 echo "</div>\n";
1408 * Display the form with options for which questions are displayed and how they are displayed.
1409 * @param bool $showquestiontext Display the text of the question within the list.
1411 protected function display_options_form($showquestiontext) {
1412 global $PAGE;
1414 echo '<form method="get" action="edit.php" id="displayoptions">';
1415 echo "<fieldset class='invisiblefieldset'>";
1416 echo html_writer::input_hidden_params($this->baseurl, array('recurse', 'showhidden', 'qbshowtext'));
1418 foreach ($this->searchconditions as $searchcondition) {
1419 echo $searchcondition->display_options($this);
1421 $this->display_showtext_checkbox($showquestiontext);
1422 $this->display_advanced_search_form();
1423 $PAGE->requires->yui_module('moodle-question-searchform', 'M.question.searchform.init');
1424 echo '<noscript><div class="centerpara"><input type="submit" value="'. get_string('go') .'" />';
1425 echo '</div></noscript></fieldset></form>';
1429 * Print the "advanced" UI elements for the form to select which questions. Hidden by default.
1431 protected function display_advanced_search_form() {
1432 print_collapsible_region_start('', 'advancedsearch', get_string('advancedsearchoptions', 'question'),
1433 'question_bank_advanced_search');
1434 foreach ($this->searchconditions as $searchcondition) {
1435 echo $searchcondition->display_options_adv($this);
1437 print_collapsible_region_end();
1441 * Display the checkbox UI for toggling the display of the question text in the list.
1442 * @param bool $showquestiontext the current or default value for whether to display the text.
1444 protected function display_showtext_checkbox($showquestiontext) {
1445 echo '<div>';
1446 echo html_writer::empty_tag('input', array('type' => 'hidden', 'name' => 'qbshowtext',
1447 'value' => 0, 'id' => 'qbshowtext_off'));
1448 echo html_writer::checkbox('qbshowtext', '1', $showquestiontext, get_string('showquestiontext', 'question'),
1449 array('id' => 'qbshowtext_on', 'class' => 'searchoptions'));
1450 echo "</div>\n";
1453 protected function create_new_question_form($category, $canadd) {
1454 global $CFG;
1455 echo '<div class="createnewquestion">';
1456 if ($canadd) {
1457 create_new_question_button($category->id, $this->editquestionurl->params(),
1458 get_string('createnewquestion', 'question'));
1459 } else {
1460 print_string('nopermissionadd', 'question');
1462 echo '</div>';
1466 * Prints the table of questions in a category with interactions
1468 * @param array $contexts Not used!
1469 * @param moodle_url $pageurl The URL to reload this page.
1470 * @param string $categoryandcontext 'categoryID,contextID'.
1471 * @param stdClass $cm Not used!
1472 * @param bool $recurse Whether to include subcategories.
1473 * @param int $page The number of the page to be displayed
1474 * @param int $perpage Number of questions to show per page
1475 * @param bool $showhidden whether deleted questions should be displayed.
1476 * @param bool $showquestiontext whether the text of each question should be shown in the list. Deprecated.
1477 * @param array $addcontexts contexts where the user is allowed to add new questions.
1479 protected function display_question_list($contexts, $pageurl, $categoryandcontext,
1480 $cm = null, $recurse=1, $page=0, $perpage=100, $showhidden=false,
1481 $showquestiontext = false, $addcontexts = array()) {
1482 global $CFG, $DB, $OUTPUT;
1484 $category = $this->get_current_category($categoryandcontext);
1486 $cmoptions = new stdClass();
1487 $cmoptions->hasattempts = !empty($this->quizhasattempts);
1489 $strselectall = get_string('selectall');
1490 $strselectnone = get_string('deselectall');
1491 $strdelete = get_string('delete');
1493 list($categoryid, $contextid) = explode(',', $categoryandcontext);
1494 $catcontext = context::instance_by_id($contextid);
1496 $canadd = has_capability('moodle/question:add', $catcontext);
1497 $caneditall =has_capability('moodle/question:editall', $catcontext);
1498 $canuseall =has_capability('moodle/question:useall', $catcontext);
1499 $canmoveall =has_capability('moodle/question:moveall', $catcontext);
1501 $this->create_new_question_form($category, $canadd);
1503 $this->build_query();
1504 $totalnumber = $this->get_question_count();
1505 if ($totalnumber == 0) {
1506 return;
1508 $questions = $this->load_page_questions($page, $perpage);
1510 echo '<div class="categorypagingbarcontainer">';
1511 $pageing_url = new moodle_url('edit.php');
1512 $r = $pageing_url->params($pageurl->params());
1513 $pagingbar = new paging_bar($totalnumber, $page, $perpage, $pageing_url);
1514 $pagingbar->pagevar = 'qpage';
1515 echo $OUTPUT->render($pagingbar);
1516 echo '</div>';
1518 echo '<form method="post" action="edit.php">';
1519 echo '<fieldset class="invisiblefieldset" style="display: block;">';
1520 echo '<input type="hidden" name="sesskey" value="'.sesskey().'" />';
1521 echo html_writer::input_hidden_params($this->baseurl);
1523 echo '<div class="categoryquestionscontainer">';
1524 $this->start_table();
1525 $rowcount = 0;
1526 foreach ($questions as $question) {
1527 $this->print_table_row($question, $rowcount);
1528 $rowcount += 1;
1530 $this->end_table();
1531 echo "</div>\n";
1533 echo '<div class="categorypagingbarcontainer pagingbottom">';
1534 echo $OUTPUT->render($pagingbar);
1535 if ($totalnumber > DEFAULT_QUESTIONS_PER_PAGE) {
1536 if ($perpage == DEFAULT_QUESTIONS_PER_PAGE) {
1537 $url = new moodle_url('edit.php', array_merge($pageurl->params(), array('qperpage'=>1000)));
1538 $showall = '<a href="'.$url.'">'.get_string('showall', 'moodle', $totalnumber).'</a>';
1539 } else {
1540 $url = new moodle_url('edit.php', array_merge($pageurl->params(), array('qperpage'=>DEFAULT_QUESTIONS_PER_PAGE)));
1541 $showall = '<a href="'.$url.'">'.get_string('showperpage', 'moodle', DEFAULT_QUESTIONS_PER_PAGE).'</a>';
1543 echo "<div class='paging'>$showall</div>";
1545 echo '</div>';
1547 echo '<div class="modulespecificbuttonscontainer">';
1548 if ($caneditall || $canmoveall || $canuseall){
1549 echo '<strong>&nbsp;'.get_string('withselected', 'question').':</strong><br />';
1551 if (function_exists('module_specific_buttons')) {
1552 echo module_specific_buttons($this->cm->id,$cmoptions);
1555 // print delete and move selected question
1556 if ($caneditall) {
1557 echo '<input type="submit" name="deleteselected" value="' . $strdelete . "\" />\n";
1560 if ($canmoveall && count($addcontexts)) {
1561 echo '<input type="submit" name="move" value="'.get_string('moveto', 'question')."\" />\n";
1562 question_category_select_menu($addcontexts, false, 0, "$category->id,$category->contextid");
1565 if (function_exists('module_specific_controls') && $canuseall) {
1566 $modulespecific = module_specific_controls($totalnumber, $recurse, $category, $this->cm->id,$cmoptions);
1567 if(!empty($modulespecific)){
1568 echo "<hr />$modulespecific";
1572 echo "</div>\n";
1574 echo '</fieldset>';
1575 echo "</form>\n";
1578 protected function start_table() {
1579 echo '<table id="categoryquestions">' . "\n";
1580 echo "<thead>\n";
1581 $this->print_table_headers();
1582 echo "</thead>\n";
1583 echo "<tbody>\n";
1586 protected function end_table() {
1587 echo "</tbody>\n";
1588 echo "</table>\n";
1591 protected function print_table_headers() {
1592 echo "<tr>\n";
1593 foreach ($this->visiblecolumns as $column) {
1594 $column->display_header();
1596 echo "</tr>\n";
1599 protected function get_row_classes($question, $rowcount) {
1600 $classes = array();
1601 if ($question->hidden) {
1602 $classes[] = 'dimmed_text';
1604 if ($question->id == $this->lastchangedid) {
1605 $classes[] ='highlight';
1607 $classes[] = 'r' . ($rowcount % 2);
1608 return $classes;
1611 protected function print_table_row($question, $rowcount) {
1612 $rowclasses = implode(' ', $this->get_row_classes($question, $rowcount));
1613 if ($rowclasses) {
1614 echo '<tr class="' . $rowclasses . '">' . "\n";
1615 } else {
1616 echo "<tr>\n";
1618 foreach ($this->visiblecolumns as $column) {
1619 $column->display($question, $rowclasses);
1621 echo "</tr>\n";
1622 foreach ($this->extrarows as $row) {
1623 $row->display($question, $rowclasses);
1627 public function process_actions() {
1628 global $CFG, $DB;
1629 /// Now, check for commands on this page and modify variables as necessary
1630 if (optional_param('move', false, PARAM_BOOL) and confirm_sesskey()) {
1631 // Move selected questions to new category
1632 $category = required_param('category', PARAM_SEQUENCE);
1633 list($tocategoryid, $contextid) = explode(',', $category);
1634 if (! $tocategory = $DB->get_record('question_categories', array('id' => $tocategoryid, 'contextid' => $contextid))) {
1635 print_error('cannotfindcate', 'question');
1637 $tocontext = context::instance_by_id($contextid);
1638 require_capability('moodle/question:add', $tocontext);
1639 $rawdata = (array) data_submitted();
1640 $questionids = array();
1641 foreach ($rawdata as $key => $value) { // Parse input for question ids
1642 if (preg_match('!^q([0-9]+)$!', $key, $matches)) {
1643 $key = $matches[1];
1644 $questionids[] = $key;
1647 if ($questionids) {
1648 list($usql, $params) = $DB->get_in_or_equal($questionids);
1649 $sql = "";
1650 $questions = $DB->get_records_sql("
1651 SELECT q.*, c.contextid
1652 FROM {question} q
1653 JOIN {question_categories} c ON c.id = q.category
1654 WHERE q.id $usql", $params);
1655 foreach ($questions as $question){
1656 question_require_capability_on($question, 'move');
1658 question_move_questions_to_category($questionids, $tocategory->id);
1659 redirect($this->baseurl->out(false,
1660 array('category' => "$tocategoryid,$contextid")));
1664 if (optional_param('deleteselected', false, PARAM_BOOL)) { // delete selected questions from the category
1665 if (($confirm = optional_param('confirm', '', PARAM_ALPHANUM)) and confirm_sesskey()) { // teacher has already confirmed the action
1666 $deleteselected = required_param('deleteselected', PARAM_RAW);
1667 if ($confirm == md5($deleteselected)) {
1668 if ($questionlist = explode(',', $deleteselected)) {
1669 // for each question either hide it if it is in use or delete it
1670 foreach ($questionlist as $questionid) {
1671 $questionid = (int)$questionid;
1672 question_require_capability_on($questionid, 'edit');
1673 if (questions_in_use(array($questionid))) {
1674 $DB->set_field('question', 'hidden', 1, array('id' => $questionid));
1675 } else {
1676 question_delete_question($questionid);
1680 redirect($this->baseurl);
1681 } else {
1682 print_error('invalidconfirm', 'question');
1687 // Unhide a question
1688 if(($unhide = optional_param('unhide', '', PARAM_INT)) and confirm_sesskey()) {
1689 question_require_capability_on($unhide, 'edit');
1690 $DB->set_field('question', 'hidden', 0, array('id' => $unhide));
1692 // Purge these questions from the cache.
1693 question_bank::notify_question_edited($unhide);
1695 redirect($this->baseurl);
1699 public function process_actions_needing_ui() {
1700 global $DB, $OUTPUT;
1701 if (optional_param('deleteselected', false, PARAM_BOOL)) {
1702 // make a list of all the questions that are selected
1703 $rawquestions = $_REQUEST; // This code is called by both POST forms and GET links, so cannot use data_submitted.
1704 $questionlist = ''; // comma separated list of ids of questions to be deleted
1705 $questionnames = ''; // string with names of questions separated by <br /> with
1706 // an asterix in front of those that are in use
1707 $inuse = false; // set to true if at least one of the questions is in use
1708 foreach ($rawquestions as $key => $value) { // Parse input for question ids
1709 if (preg_match('!^q([0-9]+)$!', $key, $matches)) {
1710 $key = $matches[1];
1711 $questionlist .= $key.',';
1712 question_require_capability_on($key, 'edit');
1713 if (questions_in_use(array($key))) {
1714 $questionnames .= '* ';
1715 $inuse = true;
1717 $questionnames .= $DB->get_field('question', 'name', array('id' => $key)) . '<br />';
1720 if (!$questionlist) { // no questions were selected
1721 redirect($this->baseurl);
1723 $questionlist = rtrim($questionlist, ',');
1725 // Add an explanation about questions in use
1726 if ($inuse) {
1727 $questionnames .= '<br />'.get_string('questionsinuse', 'question');
1729 $baseurl = new moodle_url('edit.php', $this->baseurl->params());
1730 $deleteurl = new moodle_url($baseurl, array('deleteselected'=>$questionlist, 'confirm'=>md5($questionlist), 'sesskey'=>sesskey()));
1732 echo $OUTPUT->confirm(get_string('deletequestionscheck', 'question', $questionnames), $deleteurl, $baseurl);
1734 return true;
1739 * Add another search control to this view.
1740 * @param \core_question\bank\search\condition $searchcondition the condition to add.
1742 public function add_searchcondition($searchcondition) {
1743 $this->searchconditions[] = $searchcondition;
1748 * Common setup for all pages for editing questions.
1749 * @param string $baseurl the name of the script calling this funciton. For examle 'qusetion/edit.php'.
1750 * @param string $edittab code for this edit tab
1751 * @param bool $requirecmid require cmid? default false
1752 * @param bool $requirecourseid require courseid, if cmid is not given? default true
1753 * @return array $thispageurl, $contexts, $cmid, $cm, $module, $pagevars
1755 function question_edit_setup($edittab, $baseurl, $requirecmid = false, $requirecourseid = true) {
1756 global $DB, $PAGE;
1758 $thispageurl = new moodle_url($baseurl);
1759 $thispageurl->remove_all_params(); // We are going to explicity add back everything important - this avoids unwanted params from being retained.
1761 if ($requirecmid){
1762 $cmid =required_param('cmid', PARAM_INT);
1763 } else {
1764 $cmid = optional_param('cmid', 0, PARAM_INT);
1766 if ($cmid){
1767 list($module, $cm) = get_module_from_cmid($cmid);
1768 $courseid = $cm->course;
1769 $thispageurl->params(compact('cmid'));
1770 require_login($courseid, false, $cm);
1771 $thiscontext = context_module::instance($cmid);
1772 } else {
1773 $module = null;
1774 $cm = null;
1775 if ($requirecourseid){
1776 $courseid = required_param('courseid', PARAM_INT);
1777 } else {
1778 $courseid = optional_param('courseid', 0, PARAM_INT);
1780 if ($courseid){
1781 $thispageurl->params(compact('courseid'));
1782 require_login($courseid, false);
1783 $thiscontext = context_course::instance($courseid);
1784 } else {
1785 $thiscontext = null;
1789 if ($thiscontext){
1790 $contexts = new question_edit_contexts($thiscontext);
1791 $contexts->require_one_edit_tab_cap($edittab);
1793 } else {
1794 $contexts = null;
1797 $PAGE->set_pagelayout('admin');
1799 $pagevars['qpage'] = optional_param('qpage', -1, PARAM_INT);
1801 //pass 'cat' from page to page and when 'category' comes from a drop down menu
1802 //then we also reset the qpage so we go to page 1 of
1803 //a new cat.
1804 $pagevars['cat'] = optional_param('cat', 0, PARAM_SEQUENCE); // if empty will be set up later
1805 if ($category = optional_param('category', 0, PARAM_SEQUENCE)) {
1806 if ($pagevars['cat'] != $category) { // is this a move to a new category?
1807 $pagevars['cat'] = $category;
1808 $pagevars['qpage'] = 0;
1811 if ($pagevars['cat']){
1812 $thispageurl->param('cat', $pagevars['cat']);
1814 if (strpos($baseurl, '/question/') === 0) {
1815 navigation_node::override_active_url($thispageurl);
1818 if ($pagevars['qpage'] > -1) {
1819 $thispageurl->param('qpage', $pagevars['qpage']);
1820 } else {
1821 $pagevars['qpage'] = 0;
1824 $pagevars['qperpage'] = question_get_display_preference(
1825 'qperpage', DEFAULT_QUESTIONS_PER_PAGE, PARAM_INT, $thispageurl);
1827 for ($i = 1; $i <= question_bank_view::MAX_SORTS; $i++) {
1828 $param = 'qbs' . $i;
1829 if (!$sort = optional_param($param, '', PARAM_ALPHAEXT)) {
1830 break;
1832 $thispageurl->param($param, $sort);
1835 $defaultcategory = question_make_default_categories($contexts->all());
1837 $contextlistarr = array();
1838 foreach ($contexts->having_one_edit_tab_cap($edittab) as $context){
1839 $contextlistarr[] = "'$context->id'";
1841 $contextlist = join($contextlistarr, ' ,');
1842 if (!empty($pagevars['cat'])){
1843 $catparts = explode(',', $pagevars['cat']);
1844 if (!$catparts[0] || (false !== array_search($catparts[1], $contextlistarr)) ||
1845 !$DB->count_records_select("question_categories", "id = ? AND contextid = ?", array($catparts[0], $catparts[1]))) {
1846 print_error('invalidcategory', 'question');
1848 } else {
1849 $category = $defaultcategory;
1850 $pagevars['cat'] = "$category->id,$category->contextid";
1853 // Display options.
1854 $pagevars['recurse'] = question_get_display_preference('recurse', 1, PARAM_BOOL, $thispageurl);
1855 $pagevars['showhidden'] = question_get_display_preference('showhidden', 0, PARAM_BOOL, $thispageurl);
1856 $pagevars['qbshowtext'] = question_get_display_preference('qbshowtext', 0, PARAM_BOOL, $thispageurl);
1858 // Category list page.
1859 $pagevars['cpage'] = optional_param('cpage', 1, PARAM_INT);
1860 if ($pagevars['cpage'] != 1){
1861 $thispageurl->param('cpage', $pagevars['cpage']);
1864 return array($thispageurl, $contexts, $cmid, $cm, $module, $pagevars);
1868 * Get a particular question preference that is also stored as a user preference.
1869 * If the the value is given in the GET/POST request, then that value is used,
1870 * and the user preference is updated to that value. Otherwise, the last set
1871 * value of the user preference is used, or if it has never been set the default
1872 * passed to this function.
1874 * @param string $param the param name. The URL parameter set, and the GET/POST
1875 * parameter read. The user_preference name is 'question_bank_' . $param.
1876 * @param mixed $default The default value to use, if not otherwise set.
1877 * @param int $type one of the PARAM_... constants.
1878 * @param moodle_url $thispageurl if the value has been explicitly set, we add
1879 * it to this URL.
1880 * @return mixed the parameter value to use.
1882 function question_get_display_preference($param, $default, $type, $thispageurl) {
1883 $submittedvalue = optional_param($param, null, $type);
1884 if (is_null($submittedvalue)) {
1885 return get_user_preferences('question_bank_' . $param, $default);
1888 set_user_preference('question_bank_' . $param, $submittedvalue);
1889 $thispageurl->param($param, $submittedvalue);
1890 return $submittedvalue;
1894 * Make sure user is logged in as required in this context.
1896 function require_login_in_context($contextorid = null){
1897 global $DB, $CFG;
1898 if (!is_object($contextorid)){
1899 $context = context::instance_by_id($contextorid, IGNORE_MISSING);
1900 } else {
1901 $context = $contextorid;
1903 if ($context && ($context->contextlevel == CONTEXT_COURSE)) {
1904 require_login($context->instanceid);
1905 } else if ($context && ($context->contextlevel == CONTEXT_MODULE)) {
1906 if ($cm = $DB->get_record('course_modules',array('id' =>$context->instanceid))) {
1907 if (!$course = $DB->get_record('course', array('id' => $cm->course))) {
1908 print_error('invalidcourseid');
1910 require_course_login($course, true, $cm);
1912 } else {
1913 print_error('invalidcoursemodule');
1915 } else if ($context && ($context->contextlevel == CONTEXT_SYSTEM)) {
1916 if (!empty($CFG->forcelogin)) {
1917 require_login();
1920 } else {
1921 require_login();
1926 * Print a form to let the user choose which question type to add.
1927 * When the form is submitted, it goes to the question.php script.
1928 * @param $hiddenparams hidden parameters to add to the form, in addition to
1929 * the qtype radio buttons.
1930 * @param $allowedqtypes optional list of qtypes that are allowed. If given, only
1931 * those qtypes will be shown. Example value array('description', 'multichoice').
1933 function print_choose_qtype_to_add_form($hiddenparams, array $allowedqtypes = null) {
1934 global $CFG, $PAGE, $OUTPUT;
1936 echo '<div id="chooseqtypehead" class="hd">' . "\n";
1937 echo $OUTPUT->heading(get_string('chooseqtypetoadd', 'question'), 3);
1938 echo "</div>\n";
1939 echo '<div id="chooseqtype">' . "\n";
1940 echo '<form action="' . $CFG->wwwroot . '/question/question.php" method="get"><div id="qtypeformdiv">' . "\n";
1941 foreach ($hiddenparams as $name => $value) {
1942 echo '<input type="hidden" name="' . s($name) . '" value="' . s($value) . '" />' . "\n";
1944 echo "</div>\n";
1945 echo '<div class="qtypes">' . "\n";
1946 echo '<div class="instruction">' . get_string('selectaqtypefordescription', 'question') . "</div>\n";
1947 echo '<div class="alloptions">' . "\n";
1948 echo '<div class="realqtypes">' . "\n";
1949 $fakeqtypes = array();
1950 foreach (question_bank::get_creatable_qtypes() as $qtypename => $qtype) {
1951 if ($allowedqtypes && !in_array($qtypename, $allowedqtypes)) {
1952 continue;
1954 if ($qtype->is_real_question_type()) {
1955 print_qtype_to_add_option($qtype);
1956 } else {
1957 $fakeqtypes[] = $qtype;
1960 echo "</div>\n";
1961 echo '<div class="fakeqtypes">' . "\n";
1962 foreach ($fakeqtypes as $qtype) {
1963 print_qtype_to_add_option($qtype);
1965 echo "</div>\n";
1966 echo "</div>\n";
1967 echo "</div>\n";
1968 echo '<div class="submitbuttons">' . "\n";
1969 echo '<input type="submit" value="' . get_string('next') . '" id="chooseqtype_submit" />' . "\n";
1970 echo '<input type="submit" id="chooseqtypecancel" name="addcancel" value="' . get_string('cancel') . '" />' . "\n";
1971 echo "</div></form>\n";
1972 echo "</div>\n";
1974 $PAGE->requires->js('/question/qengine.js');
1975 $module = array(
1976 'name' => 'qbank',
1977 'fullpath' => '/question/qbank.js',
1978 'requires' => array('yui2-dom', 'yui2-event', 'yui2-container'),
1979 'strings' => array(),
1980 'async' => false,
1982 $PAGE->requires->js_init_call('qtype_chooser.init', array('chooseqtype'), false, $module);
1986 * Private function used by the preceding one.
1987 * @param question_type $qtype the question type.
1989 function print_qtype_to_add_option($qtype) {
1990 echo '<div class="qtypeoption">' . "\n";
1991 echo '<label for="' . $qtype->plugin_name() . '">';
1992 echo '<input type="radio" name="qtype" id="' . $qtype->plugin_name() .
1993 '" value="' . $qtype->name() . '" />';
1994 echo '<span class="qtypename">';
1995 $fakequestion = new stdClass();
1996 $fakequestion->qtype = $qtype->name();
1997 echo print_question_icon($fakequestion);
1998 echo $qtype->menu_name() . '</span><span class="qtypesummary">' .
1999 get_string('pluginnamesummary', $qtype->plugin_name());
2000 echo "</span></label>\n";
2001 echo "</div>\n";
2005 * Print a button for creating a new question. This will open question/addquestion.php,
2006 * which in turn goes to question/question.php before getting back to $params['returnurl']
2007 * (by default the question bank screen).
2009 * @param int $categoryid The id of the category that the new question should be added to.
2010 * @param array $params Other paramters to add to the URL. You need either $params['cmid'] or
2011 * $params['courseid'], and you should probably set $params['returnurl']
2012 * @param string $caption the text to display on the button.
2013 * @param string $tooltip a tooltip to add to the button (optional).
2014 * @param bool $disabled if true, the button will be disabled.
2016 function create_new_question_button($categoryid, $params, $caption, $tooltip = '', $disabled = false) {
2017 global $CFG, $PAGE, $OUTPUT;
2018 static $choiceformprinted = false;
2019 $params['category'] = $categoryid;
2020 $url = new moodle_url('/question/addquestion.php', $params);
2021 echo $OUTPUT->single_button($url, $caption, 'get', array('disabled'=>$disabled, 'title'=>$tooltip));
2023 if (!$choiceformprinted) {
2024 echo '<div id="qtypechoicecontainer">';
2025 print_choose_qtype_to_add_form(array());
2026 echo "</div>\n";
2027 $choiceformprinted = true;