2 // This file is part of Moodle - http://moodle.org/
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
18 * Functions used to show question editing interface
21 * @subpackage questionbank
22 * @copyright 1999 onwards Martin Dougiamas and others {@link http://moodle.com}
23 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
27 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) {
37 if (!$cmrec = $DB->get_record_sql("SELECT cm.*, md.name as modname
38 FROM {course_modules} cm,
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);
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 ) {
63 // Build sql bit for $noparent
66 $npsql = " and parent='0' ";
69 // Get list of categories
71 $categorylist = question_categorylist($category->id
);
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
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.
89 $qtype->get_question_options($question);
90 $qresults[] = $question;
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) {
102 return 1 == $DB->count_records_sql("
104 FROM {question_categories} c1,
105 {question_categories} c2
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) {
118 if (question_is_only_toplevel_category_in_context($todelete)) {
119 print_error('cannotdeletecate', 'question');
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
139 /** @var bool determine whether the column is td or th. */
140 protected $isheading = false;
144 * @param $qbank the question_bank_view we are helping to render.
146 public function __construct(question_bank_view
$qbank) {
147 $this->qbank
= $qbank;
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() {
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)) {
180 echo '<div class="title">' . $title . '</div>';
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);
192 echo '<span title="' . $tip . '">';
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() {
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;
229 $newsortreverse = $currentsort > 0;
234 if ($newsortreverse) {
235 $tip = get_string('sortbyxreverse', '', $tip);
237 $tip = get_string('sortbyx', '', $tip);
239 $link = '<a href="' . $this->qbank
->new_sort_url($sort, $newsortreverse) . '" title="' . $tip . '">';
242 $link .= $this->get_sort_icon($currentsort < 0);
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) {
256 return $OUTPUT->pix_icon('t/sort_desc', get_string('desc'), '', array('class' => 'iconsort'));
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) {
281 $attr = array('class' => $this->get_classes());
282 if ($this->isheading
) {
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() {
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) {
327 if ($this->isheading
) {
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() {
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() {
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
365 * 'firstname' => array('field' => 'uc.firstname', 'title' => get_string('firstname')),
366 * 'lastname' => array('field' => 'uc.lastname', 'field' => get_string('lastname')),
368 * As well as field, and field, you can also add 'revers' => 1 if you want the default sort
370 * @return mixed as above.
372 public function is_sortable() {
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) {
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']));
402 throw new coding_exception('Unexpected $subsort type: ' . $subsort);
404 } else if ($sortable) {
405 return $sortable . $this->sortorder($reverse);
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() {
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) {
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');
447 'fullpath' => '/question/qbank.js',
448 'requires' => array('yui2-dom', 'yui2-event', 'yui2-container'),
449 'strings' => array(),
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() {
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() {
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
;
525 protected function display_content($question, $rowclasses) {
526 $labelfor = $this->label_for($question);
528 echo '<label for="' . $labelfor . '">';
530 echo format_string($question->name
);
536 public function get_required_fields() {
537 return array('q.id', 'q.name');
540 public function is_sortable() {
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
)) {
564 $u = username_load_fields_from_object($u, $question, 'creator');
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() {
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
)) {
609 $u = username_load_fields_from_object($u, $question, 'modifier');
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() {
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() {
648 public function get_extra_classes() {
649 return array('iconcol');
652 protected function print_icon($icon, $title, $url) {
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
{
675 public function init() {
677 $this->stredit
= get_string('edit');
678 $this->strview
= get_string('view');
681 public function get_name() {
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'). */
704 public function init() {
706 $this->strcopy
= get_string('duplicate');
709 public function get_name() {
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 protected $strpreview;
733 public function init() {
735 $this->strpreview
= get_string('preview');
738 public function get_name() {
739 return 'previewaction';
742 protected function display_content($question, $rowclasses) {
744 if (question_has_capability_on($question, 'use')) {
746 $image = $OUTPUT->pix_icon('t/preview', $this->strpreview
, '', array('class' => 'iconsmall'));
748 $link = $this->qbank
->preview_question_url($question);
749 $action = new popup_action('click', $link, 'questionpreview',
750 question_preview_popup_params());
752 echo $OUTPUT->action_link($link, $image, $action, array('title' => $this->strpreview
));
756 public function get_required_fields() {
757 return array('q.id');
763 * action to delete (or hide) a question, or restore a previously hidden question.
765 * @copyright 2009 Tim Hunt
766 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
768 class question_bank_delete_action_column
extends question_bank_action_column_base
{
769 protected $strdelete;
770 protected $strrestore;
772 public function init() {
774 $this->strdelete
= get_string('delete');
775 $this->strrestore
= get_string('restore');
778 public function get_name() {
779 return 'deleteaction';
782 protected function display_content($question, $rowclasses) {
783 if (question_has_capability_on($question, 'edit')) {
784 if ($question->hidden
) {
785 $url = new moodle_url($this->qbank
->base_url(), array('unhide' => $question->id
, 'sesskey'=>sesskey()));
786 $this->print_icon('t/restore', $this->strrestore
, $url);
788 $url = new moodle_url($this->qbank
->base_url(), array('deleteselected' => $question->id
, 'q' . $question->id
=> 1, 'sesskey'=>sesskey()));
789 $this->print_icon('t/delete', $this->strdelete
, $url);
794 public function get_required_fields() {
795 return array('q.id', 'q.hidden');
800 * Base class for 'columns' that are actually displayed as a row following the main question row.
802 * @copyright 2009 Tim Hunt
803 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
805 abstract class question_bank_row_base
extends question_bank_column_base
{
806 public function is_extra_row() {
810 protected function display_start($question, $rowclasses) {
812 echo '<tr class="' . $rowclasses . '">' . "\n";
816 echo '<td colspan="' . $this->qbank
->get_column_count() . '" class="' . $this->get_name() . '">';
819 protected function display_end($question, $rowclasses) {
825 * A column type for the name of the question name.
827 * @copyright 2009 Tim Hunt
828 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
830 class question_bank_question_text_row
extends question_bank_row_base
{
831 protected $formatoptions;
833 protected function init() {
834 $this->formatoptions
= new stdClass();
835 $this->formatoptions
->noclean
= true;
836 $this->formatoptions
->para
= false;
839 public function get_name() {
840 return 'questiontext';
843 protected function get_title() {
844 return get_string('questiontext', 'question');
847 protected function display_content($question, $rowclasses) {
848 $text = question_rewrite_question_preview_urls($question->questiontext
, $question->id
,
849 $question->contextid
, 'question', 'questiontext', $question->id
,
850 $question->contextid
, 'core_question');
851 $text = format_text($text, $question->questiontextformat
,
852 $this->formatoptions
);
859 public function get_extra_joins() {
860 return array('qc' => 'JOIN {question_categories} qc ON qc.id = q.category');
863 public function get_required_fields() {
864 return array('q.id', 'q.questiontext', 'q.questiontextformat', 'qc.contextid');
869 * This class prints a view of the question bank, including
870 * + Some controls to allow users to to select what is displayed.
871 * + A list of questions as a table.
872 * + Further controls to do things with the questions.
874 * This class gives a basic view, and provides plenty of hooks where subclasses
875 * can override parts of the display.
877 * The list of questions presented as a table is generated by creating a list of
878 * question_bank_column objects, one for each 'column' to be displayed. These
880 * + outputting the contents of that column, given a $question object, but also
881 * + generating the right fragments of SQL to ensure the necessary data is present,
882 * and sorted in the right order.
883 * + outputting table headers.
885 * @copyright 2009 Tim Hunt
886 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
888 class question_bank_view
{
892 protected $editquestionurl;
893 protected $quizorcourseid;
897 protected $knowncolumntypes;
898 protected $visiblecolumns;
899 protected $extrarows;
900 protected $requiredcolumns;
902 protected $lastchangedid;
905 protected $sqlparams;
906 /** @var array of \core_question\bank\search\condition objects. */
907 protected $searchconditions = array();
911 * @param question_edit_contexts $contexts
912 * @param moodle_url $pageurl
913 * @param object $course course settings
914 * @param object $cm (optional) activity settings.
916 public function __construct($contexts, $pageurl, $course, $cm = null) {
919 $this->contexts
= $contexts;
920 $this->baseurl
= $pageurl;
921 $this->course
= $course;
924 if (!empty($cm) && $cm->modname
== 'quiz') {
925 $this->quizorcourseid
= '&quizid=' . $cm->instance
;
927 $this->quizorcourseid
= '&courseid=' .$this->course
->id
;
930 // Create the url of the new question page to forward to.
931 $returnurl = $pageurl->out_as_local_url(false);
932 $this->editquestionurl
= new moodle_url('/question/question.php',
933 array('returnurl' => $returnurl));
935 $this->editquestionurl
->param('cmid', $cm->id
);
937 $this->editquestionurl
->param('courseid', $this->course
->id
);
940 $this->lastchangedid
= optional_param('lastchanged',0,PARAM_INT
);
942 $this->init_column_types();
943 $this->init_columns($this->wanted_columns(), $this->heading_column());
945 $this->init_search_conditions($this->contexts
, $this->course
, $this->cm
);
949 * Initialize search conditions from plugins
950 * local_*_get_question_bank_search_conditions() must return an array of
951 * \core_question\bank\search\condition objects.
953 protected function init_search_conditions() {
954 $searchplugins = get_plugin_list_with_function('local', 'get_question_bank_search_conditions');
955 foreach ($searchplugins as $component => $function) {
956 foreach ($function($this) as $searchobject) {
957 $this->add_searchcondition($searchobject);
962 protected function wanted_columns() {
963 $columns = array('checkbox', 'qtype', 'questionname', 'editaction', 'copyaction',
964 'previewaction', 'deleteaction', 'creatorname', 'modifiername');
965 if (question_get_display_preference('qbshowtext', 0, PARAM_BOOL
, new moodle_url(''))) {
966 $columns[] = 'questiontext';
972 * Specify the column heading
974 * @return string Column name for the heading
976 protected function heading_column() {
977 return 'questionname';
980 protected function known_field_types() {
982 new question_bank_checkbox_column($this),
983 new question_bank_question_type_column($this),
984 new question_bank_question_name_column($this),
985 new question_bank_creator_name_column($this),
986 new question_bank_modifier_name_column($this),
987 new question_bank_edit_action_column($this),
988 new question_bank_copy_action_column($this),
989 new question_bank_preview_action_column($this),
990 new question_bank_delete_action_column($this),
991 new question_bank_question_text_row($this),
995 protected function init_column_types() {
996 $this->knowncolumntypes
= array();
997 foreach ($this->known_field_types() as $col) {
998 $this->knowncolumntypes
[$col->get_name()] = $col;
1003 * Initializing table columns
1005 * @param array $wanted Collection of column names
1006 * @param string $heading The name of column that is set as heading
1008 protected function init_columns($wanted, $heading = '') {
1009 $this->visiblecolumns
= array();
1010 $this->extrarows
= array();
1011 foreach ($wanted as $colname) {
1012 if (!isset($this->knowncolumntypes
[$colname])) {
1013 throw new coding_exception('Unknown column type ' . $colname . ' requested in init columns.');
1015 $column = $this->knowncolumntypes
[$colname];
1016 if ($column->is_extra_row()) {
1017 $this->extrarows
[$colname] = $column;
1019 $this->visiblecolumns
[$colname] = $column;
1022 $this->requiredcolumns
= array_merge($this->visiblecolumns
, $this->extrarows
);
1023 if (array_key_exists($heading, $this->requiredcolumns
)) {
1024 $this->requiredcolumns
[$heading]->set_as_heading();
1029 * @param string $colname a column internal name.
1030 * @return bool is this column included in the output?
1032 public function has_column($colname) {
1033 return isset($this->visiblecolumns
[$colname]);
1037 * @return int The number of columns in the table.
1039 public function get_column_count() {
1040 return count($this->visiblecolumns
);
1043 public function get_courseid() {
1044 return $this->course
->id
;
1047 protected function init_sort() {
1048 $this->init_sort_from_params();
1049 if (empty($this->sort
)) {
1050 $this->sort
= $this->default_sort();
1055 * Deal with a sort name of the form columnname, or colname_subsort by
1056 * breaking it up, validating the bits that are presend, and returning them.
1057 * If there is no subsort, then $subsort is returned as ''.
1058 * @return array array($colname, $subsort).
1060 protected function parse_subsort($sort) {
1062 if (strpos($sort, '_') !== false) {
1063 list($colname, $subsort) = explode('_', $sort, 2);
1068 /// Validate the column name.
1069 if (!isset($this->knowncolumntypes
[$colname]) ||
!$this->knowncolumntypes
[$colname]->is_sortable()) {
1070 for ($i = 1; $i <= question_bank_view
::MAX_SORTS
; $i++
) {
1071 $this->baseurl
->remove_params('qbs' . $i);
1073 throw new moodle_exception('unknownsortcolumn', '', $link = $this->baseurl
->out(), $colname);
1075 /// Validate the subsort, if present.
1077 $subsorts = $this->knowncolumntypes
[$colname]->is_sortable();
1078 if (!is_array($subsorts) ||
!isset($subsorts[$subsort])) {
1079 throw new moodle_exception('unknownsortcolumn', '', $link = $this->baseurl
->out(), $sort);
1082 return array($colname, $subsort);
1085 protected function init_sort_from_params() {
1086 $this->sort
= array();
1087 for ($i = 1; $i <= question_bank_view
::MAX_SORTS
; $i++
) {
1088 if (!$sort = optional_param('qbs' . $i, '', PARAM_ALPHAEXT
)) {
1091 // Work out the appropriate order.
1093 if ($sort[0] == '-') {
1095 $sort = substr($sort, 1);
1100 // Deal with subsorts.
1101 list($colname, $subsort) = $this->parse_subsort($sort);
1102 $this->requiredcolumns
[$colname] = $this->knowncolumntypes
[$colname];
1103 $this->sort
[$sort] = $order;
1107 protected function sort_to_params($sorts) {
1110 foreach ($sorts as $sort => $order) {
1113 $sort = '-' . $sort;
1115 $params['qbs' . $i] = $sort;
1120 protected function default_sort() {
1121 $this->requiredcolumns
['qtype'] = $this->knowncolumntypes
['qtype'];
1122 $this->requiredcolumns
['questionname'] = $this->knowncolumntypes
['questionname'];
1123 return array('qtype' => 1, 'questionname' => 1);
1127 * @param $sort a column or column_subsort name.
1128 * @return int the current sort order for this column -1, 0, 1
1130 public function get_primary_sort_order($sort) {
1131 $order = reset($this->sort
);
1132 $primarysort = key($this->sort
);
1133 if ($sort == $primarysort) {
1141 * Get a URL to redisplay the page with a new sort for the question bank.
1142 * @param string $sort the column, or column_subsort to sort on.
1143 * @param bool $newsortreverse whether to sort in reverse order.
1144 * @return string The new URL.
1146 public function new_sort_url($sort, $newsortreverse) {
1147 if ($newsortreverse) {
1152 // Tricky code to add the new sort at the start, removing it from where it was before, if it was present.
1153 $newsort = array_reverse($this->sort
);
1154 if (isset($newsort[$sort])) {
1155 unset($newsort[$sort]);
1157 $newsort[$sort] = $order;
1158 $newsort = array_reverse($newsort);
1159 if (count($newsort) > question_bank_view
::MAX_SORTS
) {
1160 $newsort = array_slice($newsort, 0, question_bank_view
::MAX_SORTS
, true);
1162 return $this->baseurl
->out(true, $this->sort_to_params($newsort));
1166 * Create the SQL query to retrieve the indicated questions
1167 * @param stdClass $category no longer used.
1168 * @param bool $recurse no longer used.
1169 * @param bool $showhidden no longer used.
1170 * @deprecated since Moodle 2.7 MDL-40313.
1171 * @see build_query()
1172 * @see \core_question\bank\search\condition
1173 * @todo MDL-41978 This will be deleted in Moodle 2.8
1175 protected function build_query_sql($category, $recurse, $showhidden) {
1176 debugging('build_query_sql() is deprecated, please use question_bank_view::build_query() and ' .
1177 '\core_question\bank\search\condition classes instead.', DEBUG_DEVELOPER
);
1178 self
::build_query();
1182 * Create the SQL query to retrieve the indicated questions, based on
1183 * \core_question\bank\search\condition filters.
1185 protected function build_query() {
1188 /// Get the required tables.
1190 foreach ($this->requiredcolumns
as $column) {
1191 $extrajoins = $column->get_extra_joins();
1192 foreach ($extrajoins as $prefix => $join) {
1193 if (isset($joins[$prefix]) && $joins[$prefix] != $join) {
1194 throw new coding_exception('Join ' . $join . ' conflicts with previous join ' . $joins[$prefix]);
1196 $joins[$prefix] = $join;
1200 /// Get the required fields.
1201 $fields = array('q.hidden', 'q.category');
1202 foreach ($this->visiblecolumns
as $column) {
1203 $fields = array_merge($fields, $column->get_required_fields());
1205 foreach ($this->extrarows
as $row) {
1206 $fields = array_merge($fields, $row->get_required_fields());
1208 $fields = array_unique($fields);
1210 /// Build the order by clause.
1212 foreach ($this->sort
as $sort => $order) {
1213 list($colname, $subsort) = $this->parse_subsort($sort);
1214 $sorts[] = $this->requiredcolumns
[$colname]->sort_expression($order < 0, $subsort);
1217 /// Build the where clause.
1218 $tests = array('q.parent = 0');
1219 $this->sqlparams
= array();
1220 foreach ($this->searchconditions
as $searchcondition) {
1221 if ($searchcondition->where()) {
1222 $tests[] = '((' . $searchcondition->where() .'))';
1224 if ($searchcondition->params()) {
1225 $this->sqlparams
= array_merge($this->sqlparams
, $searchcondition->params());
1229 $sql = ' FROM {question} q ' . implode(' ', $joins);
1230 $sql .= ' WHERE ' . implode(' AND ', $tests);
1231 $this->countsql
= 'SELECT count(1)' . $sql;
1232 $this->loadsql
= 'SELECT ' . implode(', ', $fields) . $sql . ' ORDER BY ' . implode(', ', $sorts);
1235 protected function get_question_count() {
1237 return $DB->count_records_sql($this->countsql
, $this->sqlparams
);
1240 protected function load_page_questions($page, $perpage) {
1242 $questions = $DB->get_recordset_sql($this->loadsql
, $this->sqlparams
, $page*$perpage, $perpage);
1243 if (!$questions->valid()) {
1244 /// No questions on this page. Reset to page 0.
1245 $questions = $DB->get_recordset_sql($this->loadsql
, $this->sqlparams
, 0, $perpage);
1250 public function base_url() {
1251 return $this->baseurl
;
1254 public function edit_question_url($questionid) {
1255 return $this->editquestionurl
->out(true, array('id' => $questionid));
1259 * Get the URL for duplicating a given question.
1260 * @param int $questionid the question id.
1261 * @return moodle_url the URL.
1263 public function copy_question_url($questionid) {
1264 return $this->editquestionurl
->out(true, array('id' => $questionid, 'makecopy' => 1));
1267 public function preview_question_url($question) {
1268 return question_preview_url($question->id
, null, null, null, null,
1269 $this->contexts
->lowest());
1273 * Shows the question bank editing interface.
1275 * The function also processes a number of actions:
1277 * Actions affecting the question pool:
1278 * move Moves a question to a different category
1279 * deleteselected Deletes the selected questions from the category
1281 * category Chooses the category
1282 * displayoptions Sets display options
1284 public function display($tabname, $page, $perpage, $cat,
1285 $recurse, $showhidden, $showquestiontext) {
1286 global $PAGE, $OUTPUT;
1288 if ($this->process_actions_needing_ui()) {
1291 $editcontexts = $this->contexts
->having_one_edit_tab_cap($tabname);
1292 // Category selection form
1293 echo $OUTPUT->heading(get_string('questionbank', 'question'), 2);
1294 array_unshift($this->searchconditions
, new \core_question\bank\search\
hidden_condition(!$showhidden));
1295 array_unshift($this->searchconditions
, new \core_question\bank\search\
category_condition(
1296 $cat, $recurse, $editcontexts, $this->baseurl
, $this->course
));
1297 $this->display_options_form($showquestiontext);
1299 // continues with list of questions
1300 $this->display_question_list($this->contexts
->having_one_edit_tab_cap($tabname),
1301 $this->baseurl
, $cat, $this->cm
,
1302 null, $page, $perpage, $showhidden, $showquestiontext,
1303 $this->contexts
->having_cap('moodle/question:add'));
1306 protected function print_choose_category_message($categoryandcontext) {
1307 echo "<p style=\"text-align:center;\"><b>";
1308 print_string('selectcategoryabove', 'question');
1312 protected function get_current_category($categoryandcontext) {
1313 global $DB, $OUTPUT;
1314 list($categoryid, $contextid) = explode(',', $categoryandcontext);
1316 $this->print_choose_category_message($categoryandcontext);
1320 if (!$category = $DB->get_record('question_categories',
1321 array('id' => $categoryid, 'contextid' => $contextid))) {
1322 echo $OUTPUT->box_start('generalbox questionbank');
1323 echo $OUTPUT->notification('Category not found!');
1324 echo $OUTPUT->box_end();
1332 * prints category information
1333 * @param stdClass $category the category row from the database.
1334 * @deprecated since Moodle 2.7 MDL-40313.
1335 * @see \core_question\bank\search\condition
1336 * @todo MDL-41978 This will be deleted in Moodle 2.8
1338 protected function print_category_info($category) {
1339 $formatoptions = new stdClass();
1340 $formatoptions->noclean
= true;
1341 $formatoptions->overflowdiv
= true;
1342 echo '<div class="boxaligncenter">';
1343 echo format_text($category->info
, $category->infoformat
, $formatoptions, $this->course
->id
);
1348 * Prints a form to choose categories
1349 * @deprecated since Moodle 2.7 MDL-40313.
1350 * @see \core_question\bank\search\condition
1351 * @todo MDL-41978 This will be deleted in Moodle 2.8
1353 protected function display_category_form($contexts, $pageurl, $current) {
1356 debugging('display_category_form() is deprecated, please use ' .
1357 '\core_question\bank\search\condition instead.', DEBUG_DEVELOPER
);
1358 /// Get all the existing categories now
1359 echo '<div class="choosecategory">';
1360 $catmenu = question_category_options($contexts, false, 0, true);
1362 $select = new single_select($this->baseurl
, 'category', $catmenu, $current, null, 'catmenu');
1363 $select->set_label(get_string('selectacategory', 'question'));
1364 echo $OUTPUT->render($select);
1369 * Display the options form.
1370 * @param bool $recurse no longer used.
1371 * @param bool $showhidden no longer used.
1372 * @param bool $showquestiontext whether to show the question text.
1373 * @deprecated since Moodle 2.7 MDL-40313.
1374 * @see display_options_form
1375 * @todo MDL-41978 This will be deleted in Moodle 2.8
1376 * @see \core_question\bank\search\condition
1378 protected function display_options($recurse, $showhidden, $showquestiontext) {
1379 debugging('display_options() is deprecated, please use display_options_form instead.', DEBUG_DEVELOPER
);
1380 return $this->display_options_form($showquestiontext);
1384 * Print a single option checkbox.
1385 * @deprecated since Moodle 2.7 MDL-40313.
1386 * @see \core_question\bank\search\condition
1387 * @see html_writer::checkbox
1388 * @todo MDL-41978 This will be deleted in Moodle 2.8
1390 protected function display_category_form_checkbox($name, $value, $label) {
1391 debugging('display_category_form_checkbox() is deprecated, ' .
1392 'please use \core_question\bank\search\condition instead.', DEBUG_DEVELOPER
);
1393 echo '<div><input type="hidden" id="' . $name . '_off" name="' . $name . '" value="0" />';
1394 echo '<input type="checkbox" id="' . $name . '_on" name="' . $name . '" value="1"';
1396 echo ' checked="checked"';
1398 echo ' onchange="getElementById(\'displayoptions\').submit(); return true;" />';
1399 echo '<label for="' . $name . '_on">' . $label . '</label>';
1404 * Display the form with options for which questions are displayed and how they are displayed.
1405 * @param bool $showquestiontext Display the text of the question within the list.
1407 protected function display_options_form($showquestiontext) {
1410 echo '<form method="get" action="edit.php" id="displayoptions">';
1411 echo "<fieldset class='invisiblefieldset'>";
1412 echo html_writer
::input_hidden_params($this->baseurl
, array('recurse', 'showhidden', 'qbshowtext'));
1414 foreach ($this->searchconditions
as $searchcondition) {
1415 echo $searchcondition->display_options($this);
1417 $this->display_showtext_checkbox($showquestiontext);
1418 $this->display_advanced_search_form();
1419 $PAGE->requires
->yui_module('moodle-question-searchform', 'M.question.searchform.init');
1420 echo '<noscript><div class="centerpara"><input type="submit" value="'. get_string('go') .'" />';
1421 echo '</div></noscript></fieldset></form>';
1425 * Print the "advanced" UI elements for the form to select which questions. Hidden by default.
1427 protected function display_advanced_search_form() {
1428 print_collapsible_region_start('', 'advancedsearch', get_string('advancedsearchoptions', 'question'),
1429 'question_bank_advanced_search');
1430 foreach ($this->searchconditions
as $searchcondition) {
1431 echo $searchcondition->display_options_adv($this);
1433 print_collapsible_region_end();
1437 * Display the checkbox UI for toggling the display of the question text in the list.
1438 * @param bool $showquestiontext the current or default value for whether to display the text.
1440 protected function display_showtext_checkbox($showquestiontext) {
1442 echo html_writer
::empty_tag('input', array('type' => 'hidden', 'name' => 'qbshowtext',
1443 'value' => 0, 'id' => 'qbshowtext_off'));
1444 echo html_writer
::checkbox('qbshowtext', '1', $showquestiontext, get_string('showquestiontext', 'question'),
1445 array('id' => 'qbshowtext_on', 'class' => 'searchoptions'));
1449 protected function create_new_question_form($category, $canadd) {
1451 echo '<div class="createnewquestion">';
1453 create_new_question_button($category->id
, $this->editquestionurl
->params(),
1454 get_string('createnewquestion', 'question'));
1456 print_string('nopermissionadd', 'question');
1462 * Prints the table of questions in a category with interactions
1464 * @param array $contexts Not used!
1465 * @param moodle_url $pageurl The URL to reload this page.
1466 * @param string $categoryandcontext 'categoryID,contextID'.
1467 * @param stdClass $cm Not used!
1468 * @param bool $recurse Whether to include subcategories.
1469 * @param int $page The number of the page to be displayed
1470 * @param int $perpage Number of questions to show per page
1471 * @param bool $showhidden whether deleted questions should be displayed.
1472 * @param bool $showquestiontext whether the text of each question should be shown in the list. Deprecated.
1473 * @param array $addcontexts contexts where the user is allowed to add new questions.
1475 protected function display_question_list($contexts, $pageurl, $categoryandcontext,
1476 $cm = null, $recurse=1, $page=0, $perpage=100, $showhidden=false,
1477 $showquestiontext = false, $addcontexts = array()) {
1478 global $CFG, $DB, $OUTPUT;
1480 $category = $this->get_current_category($categoryandcontext);
1482 $cmoptions = new stdClass();
1483 $cmoptions->hasattempts
= !empty($this->quizhasattempts
);
1485 $strselectall = get_string('selectall');
1486 $strselectnone = get_string('deselectall');
1487 $strdelete = get_string('delete');
1489 list($categoryid, $contextid) = explode(',', $categoryandcontext);
1490 $catcontext = context
::instance_by_id($contextid);
1492 $canadd = has_capability('moodle/question:add', $catcontext);
1493 $caneditall =has_capability('moodle/question:editall', $catcontext);
1494 $canuseall =has_capability('moodle/question:useall', $catcontext);
1495 $canmoveall =has_capability('moodle/question:moveall', $catcontext);
1497 $this->create_new_question_form($category, $canadd);
1499 $this->build_query();
1500 $totalnumber = $this->get_question_count();
1501 if ($totalnumber == 0) {
1504 $questions = $this->load_page_questions($page, $perpage);
1506 echo '<div class="categorypagingbarcontainer">';
1507 $pageing_url = new moodle_url('edit.php');
1508 $r = $pageing_url->params($pageurl->params());
1509 $pagingbar = new paging_bar($totalnumber, $page, $perpage, $pageing_url);
1510 $pagingbar->pagevar
= 'qpage';
1511 echo $OUTPUT->render($pagingbar);
1514 echo '<form method="post" action="edit.php">';
1515 echo '<fieldset class="invisiblefieldset" style="display: block;">';
1516 echo '<input type="hidden" name="sesskey" value="'.sesskey().'" />';
1517 echo html_writer
::input_hidden_params($this->baseurl
);
1519 echo '<div class="categoryquestionscontainer">';
1520 $this->start_table();
1522 foreach ($questions as $question) {
1523 $this->print_table_row($question, $rowcount);
1529 echo '<div class="categorypagingbarcontainer pagingbottom">';
1530 echo $OUTPUT->render($pagingbar);
1531 if ($totalnumber > DEFAULT_QUESTIONS_PER_PAGE
) {
1532 if ($perpage == DEFAULT_QUESTIONS_PER_PAGE
) {
1533 $url = new moodle_url('edit.php', array_merge($pageurl->params(), array('qperpage'=>1000)));
1534 $showall = '<a href="'.$url.'">'.get_string('showall', 'moodle', $totalnumber).'</a>';
1536 $url = new moodle_url('edit.php', array_merge($pageurl->params(), array('qperpage'=>DEFAULT_QUESTIONS_PER_PAGE
)));
1537 $showall = '<a href="'.$url.'">'.get_string('showperpage', 'moodle', DEFAULT_QUESTIONS_PER_PAGE
).'</a>';
1539 echo "<div class='paging'>$showall</div>";
1543 echo '<div class="modulespecificbuttonscontainer">';
1544 if ($caneditall ||
$canmoveall ||
$canuseall){
1545 echo '<strong> '.get_string('withselected', 'question').':</strong><br />';
1547 if (function_exists('module_specific_buttons')) {
1548 echo module_specific_buttons($this->cm
->id
,$cmoptions);
1551 // print delete and move selected question
1553 echo '<input type="submit" name="deleteselected" value="' . $strdelete . "\" />\n";
1556 if ($canmoveall && count($addcontexts)) {
1557 echo '<input type="submit" name="move" value="'.get_string('moveto', 'question')."\" />\n";
1558 question_category_select_menu($addcontexts, false, 0, "$category->id,$category->contextid");
1561 if (function_exists('module_specific_controls') && $canuseall) {
1562 $modulespecific = module_specific_controls($totalnumber, $recurse, $category, $this->cm
->id
,$cmoptions);
1563 if(!empty($modulespecific)){
1564 echo "<hr />$modulespecific";
1574 protected function start_table() {
1575 echo '<table id="categoryquestions">' . "\n";
1577 $this->print_table_headers();
1582 protected function end_table() {
1587 protected function print_table_headers() {
1589 foreach ($this->visiblecolumns
as $column) {
1590 $column->display_header();
1595 protected function get_row_classes($question, $rowcount) {
1597 if ($question->hidden
) {
1598 $classes[] = 'dimmed_text';
1600 if ($question->id
== $this->lastchangedid
) {
1601 $classes[] ='highlight';
1603 $classes[] = 'r' . ($rowcount %
2);
1607 protected function print_table_row($question, $rowcount) {
1608 $rowclasses = implode(' ', $this->get_row_classes($question, $rowcount));
1610 echo '<tr class="' . $rowclasses . '">' . "\n";
1614 foreach ($this->visiblecolumns
as $column) {
1615 $column->display($question, $rowclasses);
1618 foreach ($this->extrarows
as $row) {
1619 $row->display($question, $rowclasses);
1623 public function process_actions() {
1625 /// Now, check for commands on this page and modify variables as necessary
1626 if (optional_param('move', false, PARAM_BOOL
) and confirm_sesskey()) {
1627 // Move selected questions to new category
1628 $category = required_param('category', PARAM_SEQUENCE
);
1629 list($tocategoryid, $contextid) = explode(',', $category);
1630 if (! $tocategory = $DB->get_record('question_categories', array('id' => $tocategoryid, 'contextid' => $contextid))) {
1631 print_error('cannotfindcate', 'question');
1633 $tocontext = context
::instance_by_id($contextid);
1634 require_capability('moodle/question:add', $tocontext);
1635 $rawdata = (array) data_submitted();
1636 $questionids = array();
1637 foreach ($rawdata as $key => $value) { // Parse input for question ids
1638 if (preg_match('!^q([0-9]+)$!', $key, $matches)) {
1640 $questionids[] = $key;
1644 list($usql, $params) = $DB->get_in_or_equal($questionids);
1646 $questions = $DB->get_records_sql("
1647 SELECT q.*, c.contextid
1649 JOIN {question_categories} c ON c.id = q.category
1650 WHERE q.id $usql", $params);
1651 foreach ($questions as $question){
1652 question_require_capability_on($question, 'move');
1654 question_move_questions_to_category($questionids, $tocategory->id
);
1655 redirect($this->baseurl
->out(false,
1656 array('category' => "$tocategoryid,$contextid")));
1660 if (optional_param('deleteselected', false, PARAM_BOOL
)) { // delete selected questions from the category
1661 if (($confirm = optional_param('confirm', '', PARAM_ALPHANUM
)) and confirm_sesskey()) { // teacher has already confirmed the action
1662 $deleteselected = required_param('deleteselected', PARAM_RAW
);
1663 if ($confirm == md5($deleteselected)) {
1664 if ($questionlist = explode(',', $deleteselected)) {
1665 // for each question either hide it if it is in use or delete it
1666 foreach ($questionlist as $questionid) {
1667 $questionid = (int)$questionid;
1668 question_require_capability_on($questionid, 'edit');
1669 if (questions_in_use(array($questionid))) {
1670 $DB->set_field('question', 'hidden', 1, array('id' => $questionid));
1672 question_delete_question($questionid);
1676 redirect($this->baseurl
);
1678 print_error('invalidconfirm', 'question');
1683 // Unhide a question
1684 if(($unhide = optional_param('unhide', '', PARAM_INT
)) and confirm_sesskey()) {
1685 question_require_capability_on($unhide, 'edit');
1686 $DB->set_field('question', 'hidden', 0, array('id' => $unhide));
1688 // Purge these questions from the cache.
1689 question_bank
::notify_question_edited($unhide);
1691 redirect($this->baseurl
);
1695 public function process_actions_needing_ui() {
1696 global $DB, $OUTPUT;
1697 if (optional_param('deleteselected', false, PARAM_BOOL
)) {
1698 // make a list of all the questions that are selected
1699 $rawquestions = $_REQUEST; // This code is called by both POST forms and GET links, so cannot use data_submitted.
1700 $questionlist = ''; // comma separated list of ids of questions to be deleted
1701 $questionnames = ''; // string with names of questions separated by <br /> with
1702 // an asterix in front of those that are in use
1703 $inuse = false; // set to true if at least one of the questions is in use
1704 foreach ($rawquestions as $key => $value) { // Parse input for question ids
1705 if (preg_match('!^q([0-9]+)$!', $key, $matches)) {
1707 $questionlist .= $key.',';
1708 question_require_capability_on($key, 'edit');
1709 if (questions_in_use(array($key))) {
1710 $questionnames .= '* ';
1713 $questionnames .= $DB->get_field('question', 'name', array('id' => $key)) . '<br />';
1716 if (!$questionlist) { // no questions were selected
1717 redirect($this->baseurl
);
1719 $questionlist = rtrim($questionlist, ',');
1721 // Add an explanation about questions in use
1723 $questionnames .= '<br />'.get_string('questionsinuse', 'question');
1725 $baseurl = new moodle_url('edit.php', $this->baseurl
->params());
1726 $deleteurl = new moodle_url($baseurl, array('deleteselected'=>$questionlist, 'confirm'=>md5($questionlist), 'sesskey'=>sesskey()));
1728 echo $OUTPUT->confirm(get_string('deletequestionscheck', 'question', $questionnames), $deleteurl, $baseurl);
1735 * Add another search control to this view.
1736 * @param \core_question\bank\search\condition $searchcondition the condition to add.
1738 public function add_searchcondition($searchcondition) {
1739 $this->searchconditions
[] = $searchcondition;
1744 * Common setup for all pages for editing questions.
1745 * @param string $baseurl the name of the script calling this funciton. For examle 'qusetion/edit.php'.
1746 * @param string $edittab code for this edit tab
1747 * @param bool $requirecmid require cmid? default false
1748 * @param bool $requirecourseid require courseid, if cmid is not given? default true
1749 * @return array $thispageurl, $contexts, $cmid, $cm, $module, $pagevars
1751 function question_edit_setup($edittab, $baseurl, $requirecmid = false, $requirecourseid = true) {
1754 $thispageurl = new moodle_url($baseurl);
1755 $thispageurl->remove_all_params(); // We are going to explicity add back everything important - this avoids unwanted params from being retained.
1758 $cmid =required_param('cmid', PARAM_INT
);
1760 $cmid = optional_param('cmid', 0, PARAM_INT
);
1763 list($module, $cm) = get_module_from_cmid($cmid);
1764 $courseid = $cm->course
;
1765 $thispageurl->params(compact('cmid'));
1766 require_login($courseid, false, $cm);
1767 $thiscontext = context_module
::instance($cmid);
1771 if ($requirecourseid){
1772 $courseid = required_param('courseid', PARAM_INT
);
1774 $courseid = optional_param('courseid', 0, PARAM_INT
);
1777 $thispageurl->params(compact('courseid'));
1778 require_login($courseid, false);
1779 $thiscontext = context_course
::instance($courseid);
1781 $thiscontext = null;
1786 $contexts = new question_edit_contexts($thiscontext);
1787 $contexts->require_one_edit_tab_cap($edittab);
1793 $PAGE->set_pagelayout('admin');
1795 $pagevars['qpage'] = optional_param('qpage', -1, PARAM_INT
);
1797 //pass 'cat' from page to page and when 'category' comes from a drop down menu
1798 //then we also reset the qpage so we go to page 1 of
1800 $pagevars['cat'] = optional_param('cat', 0, PARAM_SEQUENCE
); // if empty will be set up later
1801 if ($category = optional_param('category', 0, PARAM_SEQUENCE
)) {
1802 if ($pagevars['cat'] != $category) { // is this a move to a new category?
1803 $pagevars['cat'] = $category;
1804 $pagevars['qpage'] = 0;
1807 if ($pagevars['cat']){
1808 $thispageurl->param('cat', $pagevars['cat']);
1810 if (strpos($baseurl, '/question/') === 0) {
1811 navigation_node
::override_active_url($thispageurl);
1814 if ($pagevars['qpage'] > -1) {
1815 $thispageurl->param('qpage', $pagevars['qpage']);
1817 $pagevars['qpage'] = 0;
1820 $pagevars['qperpage'] = question_get_display_preference(
1821 'qperpage', DEFAULT_QUESTIONS_PER_PAGE
, PARAM_INT
, $thispageurl);
1823 for ($i = 1; $i <= question_bank_view
::MAX_SORTS
; $i++
) {
1824 $param = 'qbs' . $i;
1825 if (!$sort = optional_param($param, '', PARAM_ALPHAEXT
)) {
1828 $thispageurl->param($param, $sort);
1831 $defaultcategory = question_make_default_categories($contexts->all());
1833 $contextlistarr = array();
1834 foreach ($contexts->having_one_edit_tab_cap($edittab) as $context){
1835 $contextlistarr[] = "'$context->id'";
1837 $contextlist = join($contextlistarr, ' ,');
1838 if (!empty($pagevars['cat'])){
1839 $catparts = explode(',', $pagevars['cat']);
1840 if (!$catparts[0] ||
(false !== array_search($catparts[1], $contextlistarr)) ||
1841 !$DB->count_records_select("question_categories", "id = ? AND contextid = ?", array($catparts[0], $catparts[1]))) {
1842 print_error('invalidcategory', 'question');
1845 $category = $defaultcategory;
1846 $pagevars['cat'] = "$category->id,$category->contextid";
1850 $pagevars['recurse'] = question_get_display_preference('recurse', 1, PARAM_BOOL
, $thispageurl);
1851 $pagevars['showhidden'] = question_get_display_preference('showhidden', 0, PARAM_BOOL
, $thispageurl);
1852 $pagevars['qbshowtext'] = question_get_display_preference('qbshowtext', 0, PARAM_BOOL
, $thispageurl);
1854 // Category list page.
1855 $pagevars['cpage'] = optional_param('cpage', 1, PARAM_INT
);
1856 if ($pagevars['cpage'] != 1){
1857 $thispageurl->param('cpage', $pagevars['cpage']);
1860 return array($thispageurl, $contexts, $cmid, $cm, $module, $pagevars);
1864 * Get a particular question preference that is also stored as a user preference.
1865 * If the the value is given in the GET/POST request, then that value is used,
1866 * and the user preference is updated to that value. Otherwise, the last set
1867 * value of the user preference is used, or if it has never been set the default
1868 * passed to this function.
1870 * @param string $param the param name. The URL parameter set, and the GET/POST
1871 * parameter read. The user_preference name is 'question_bank_' . $param.
1872 * @param mixed $default The default value to use, if not otherwise set.
1873 * @param int $type one of the PARAM_... constants.
1874 * @param moodle_url $thispageurl if the value has been explicitly set, we add
1876 * @return mixed the parameter value to use.
1878 function question_get_display_preference($param, $default, $type, $thispageurl) {
1879 $submittedvalue = optional_param($param, null, $type);
1880 if (is_null($submittedvalue)) {
1881 return get_user_preferences('question_bank_' . $param, $default);
1884 set_user_preference('question_bank_' . $param, $submittedvalue);
1885 $thispageurl->param($param, $submittedvalue);
1886 return $submittedvalue;
1890 * Make sure user is logged in as required in this context.
1892 function require_login_in_context($contextorid = null){
1894 if (!is_object($contextorid)){
1895 $context = context
::instance_by_id($contextorid, IGNORE_MISSING
);
1897 $context = $contextorid;
1899 if ($context && ($context->contextlevel
== CONTEXT_COURSE
)) {
1900 require_login($context->instanceid
);
1901 } else if ($context && ($context->contextlevel
== CONTEXT_MODULE
)) {
1902 if ($cm = $DB->get_record('course_modules',array('id' =>$context->instanceid
))) {
1903 if (!$course = $DB->get_record('course', array('id' => $cm->course
))) {
1904 print_error('invalidcourseid');
1906 require_course_login($course, true, $cm);
1909 print_error('invalidcoursemodule');
1911 } else if ($context && ($context->contextlevel
== CONTEXT_SYSTEM
)) {
1912 if (!empty($CFG->forcelogin
)) {
1922 * Print a form to let the user choose which question type to add.
1923 * When the form is submitted, it goes to the question.php script.
1924 * @param $hiddenparams hidden parameters to add to the form, in addition to
1925 * the qtype radio buttons.
1926 * @param $allowedqtypes optional list of qtypes that are allowed. If given, only
1927 * those qtypes will be shown. Example value array('description', 'multichoice').
1929 function print_choose_qtype_to_add_form($hiddenparams, array $allowedqtypes = null) {
1930 global $CFG, $PAGE, $OUTPUT;
1932 echo '<div id="chooseqtypehead" class="hd">' . "\n";
1933 echo $OUTPUT->heading(get_string('chooseqtypetoadd', 'question'), 3);
1935 echo '<div id="chooseqtype">' . "\n";
1936 echo '<form action="' . $CFG->wwwroot
. '/question/question.php" method="get"><div id="qtypeformdiv">' . "\n";
1937 foreach ($hiddenparams as $name => $value) {
1938 echo '<input type="hidden" name="' . s($name) . '" value="' . s($value) . '" />' . "\n";
1941 echo '<div class="qtypes">' . "\n";
1942 echo '<div class="instruction">' . get_string('selectaqtypefordescription', 'question') . "</div>\n";
1943 echo '<div class="alloptions">' . "\n";
1944 echo '<div class="realqtypes">' . "\n";
1945 $fakeqtypes = array();
1946 foreach (question_bank
::get_creatable_qtypes() as $qtypename => $qtype) {
1947 if ($allowedqtypes && !in_array($qtypename, $allowedqtypes)) {
1950 if ($qtype->is_real_question_type()) {
1951 print_qtype_to_add_option($qtype);
1953 $fakeqtypes[] = $qtype;
1957 echo '<div class="fakeqtypes">' . "\n";
1958 foreach ($fakeqtypes as $qtype) {
1959 print_qtype_to_add_option($qtype);
1964 echo '<div class="submitbuttons">' . "\n";
1965 echo '<input type="submit" value="' . get_string('next') . '" id="chooseqtype_submit" />' . "\n";
1966 echo '<input type="submit" id="chooseqtypecancel" name="addcancel" value="' . get_string('cancel') . '" />' . "\n";
1967 echo "</div></form>\n";
1970 $PAGE->requires
->js('/question/qengine.js');
1973 'fullpath' => '/question/qbank.js',
1974 'requires' => array('yui2-dom', 'yui2-event', 'yui2-container'),
1975 'strings' => array(),
1978 $PAGE->requires
->js_init_call('qtype_chooser.init', array('chooseqtype'), false, $module);
1982 * Private function used by the preceding one.
1983 * @param question_type $qtype the question type.
1985 function print_qtype_to_add_option($qtype) {
1986 echo '<div class="qtypeoption">' . "\n";
1987 echo '<label for="' . $qtype->plugin_name() . '">';
1988 echo '<input type="radio" name="qtype" id="' . $qtype->plugin_name() .
1989 '" value="' . $qtype->name() . '" />';
1990 echo '<span class="qtypename">';
1991 $fakequestion = new stdClass();
1992 $fakequestion->qtype
= $qtype->name();
1993 echo print_question_icon($fakequestion);
1994 echo $qtype->menu_name() . '</span><span class="qtypesummary">' .
1995 get_string('pluginnamesummary', $qtype->plugin_name());
1996 echo "</span></label>\n";
2001 * Print a button for creating a new question. This will open question/addquestion.php,
2002 * which in turn goes to question/question.php before getting back to $params['returnurl']
2003 * (by default the question bank screen).
2005 * @param int $categoryid The id of the category that the new question should be added to.
2006 * @param array $params Other paramters to add to the URL. You need either $params['cmid'] or
2007 * $params['courseid'], and you should probably set $params['returnurl']
2008 * @param string $caption the text to display on the button.
2009 * @param string $tooltip a tooltip to add to the button (optional).
2010 * @param bool $disabled if true, the button will be disabled.
2012 function create_new_question_button($categoryid, $params, $caption, $tooltip = '', $disabled = false) {
2013 global $CFG, $PAGE, $OUTPUT;
2014 static $choiceformprinted = false;
2015 $params['category'] = $categoryid;
2016 $url = new moodle_url('/question/addquestion.php', $params);
2017 echo $OUTPUT->single_button($url, $caption, 'get', array('disabled'=>$disabled, 'title'=>$tooltip));
2019 if (!$choiceformprinted) {
2020 echo '<div id="qtypechoicecontainer">';
2021 print_choose_qtype_to_add_form(array());
2023 $choiceformprinted = true;