44f744ffaaa67eb17be4a7d0730f8790cfbcc001
[moodle.git] / question / editlib.php
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.
13 //
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
19  *
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
24  */
27 defined('MOODLE_INTERNAL') || die();
29 require_once($CFG->libdir . '/questionlib.php');
31 define('DEFAULT_QUESTIONS_PER_PAGE', 20);
33 function get_module_from_cmid($cmid) {
34     global $CFG, $DB;
35     if (!$cmrec = $DB->get_record_sql("SELECT cm.*, md.name as modname
36                                FROM {course_modules} cm,
37                                     {modules} md
38                                WHERE cm.id = ? AND
39                                      md.id = cm.module", array($cmid))){
40         print_error('invalidcoursemodule');
41     } elseif (!$modrec =$DB->get_record($cmrec->modname, array('id' => $cmrec->instance))) {
42         print_error('invalidcoursemodule');
43     }
44     $modrec->instance = $modrec->id;
45     $modrec->cmid = $cmrec->id;
46     $cmrec->name = $modrec->name;
48     return array($modrec, $cmrec);
49 }
50 /**
51 * Function to read all questions for category into big array
52 *
53 * @param int $category category number
54 * @param bool $noparent if true only questions with NO parent will be selected
55 * @param bool $recurse include subdirectories
56 * @param bool $export set true if this is called by questionbank export
57 */
58 function get_questions_category( $category, $noparent=false, $recurse=true, $export=true ) {
59     global $DB;
61     // Build sql bit for $noparent
62     $npsql = '';
63     if ($noparent) {
64       $npsql = " and parent='0' ";
65     }
67     // Get list of categories
68     if ($recurse) {
69         $categorylist = question_categorylist($category->id);
70     } else {
71         $categorylist = array($category->id);
72     }
74     // Get the list of questions for the category
75     list($usql, $params) = $DB->get_in_or_equal($categorylist);
76     $questions = $DB->get_records_select('question', "category $usql $npsql", $params, 'qtype, name');
78     // Iterate through questions, getting stuff we need
79     $qresults = array();
80     foreach($questions as $key => $question) {
81         $question->export_process = $export;
82         $qtype = question_bank::get_qtype($question->qtype, false);
83         if ($export && $qtype->name() == 'missingtype') {
84             // Unrecognised question type. Skip this question when exporting.
85             continue;
86         }
87         $qtype->get_question_options($question);
88         $qresults[] = $question;
89     }
91     return $qresults;
92 }
94 /**
95  * @param int $categoryid a category id.
96  * @return bool whether this is the only top-level category in a context.
97  */
98 function question_is_only_toplevel_category_in_context($categoryid) {
99     global $DB;
100     return 1 == $DB->count_records_sql("
101             SELECT count(*)
102               FROM {question_categories} c1,
103                    {question_categories} c2
104              WHERE c2.id = ?
105                AND c1.contextid = c2.contextid
106                AND c1.parent = 0 AND c2.parent = 0", array($categoryid));
109 /**
110  * Check whether this user is allowed to delete this category.
111  *
112  * @param int $todelete a category id.
113  */
114 function question_can_delete_cat($todelete) {
115     global $DB;
116     if (question_is_only_toplevel_category_in_context($todelete)) {
117         print_error('cannotdeletecate', 'question');
118     } else {
119         $contextid = $DB->get_field('question_categories', 'contextid', array('id' => $todelete));
120         require_capability('moodle/question:managecategory', get_context_instance_by_id($contextid));
121     }
125 /**
126  * Base class for representing a column in a {@link question_bank_view}.
127  *
128  * @copyright  2009 Tim Hunt
129  * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
130  */
131 abstract class question_bank_column_base {
132     /**
133      * @var question_bank_view
134      */
135     protected $qbank;
137     /**
138      * Constructor.
139      * @param $qbank the question_bank_view we are helping to render.
140      */
141     public function __construct(question_bank_view $qbank) {
142         $this->qbank = $qbank;
143         $this->init();
144     }
146     /**
147      * A chance for subclasses to initialise themselves, for example to load lang strings,
148      * without having to override the constructor.
149      */
150     protected function init() {
151     }
153     public function is_extra_row() {
154         return false;
155     }
157     /**
158      * Output the column header cell.
159      */
160     public function display_header() {
161         echo '<th class="header ' . $this->get_classes() . '" scope="col">';
162         $sortable = $this->is_sortable();
163         $name = $this->get_name();
164         $title = $this->get_title();
165         $tip = $this->get_title_tip();
166         if (is_array($sortable)) {
167             if ($title) {
168                 echo '<div class="title">' . $title . '</div>';
169             }
170             $links = array();
171             foreach ($sortable as $subsort => $details) {
172                 $links[] = $this->make_sort_link($name . '_' . $subsort,
173                         $details['title'], '', !empty($details['reverse']));
174             }
175             echo '<div class="sorters">' . implode(' / ', $links) . '</div>';
176         } else if ($sortable) {
177             echo $this->make_sort_link($name, $title, $tip);
178         } else {
179             if ($tip) {
180                 echo '<span title="' . $tip . '">';
181             }
182             echo $title;
183             if ($tip) {
184                 echo '</span>';
185             }
186         }
187         echo "</th>\n";
188     }
190     /**
191      * Title for this column. Not used if is_sortable returns an array.
192      * @param object $question the row from the $question table, augmented with extra information.
193      * @param string $rowclasses CSS class names that should be applied to this row of output.
194      */
195     protected abstract function get_title();
197     /**
198      * @return string a fuller version of the name. Use this when get_title() returns
199      * something very short, and you want a longer version as a tool tip.
200      */
201     protected function get_title_tip() {
202         return '';
203     }
205     /**
206      * Get a link that changes the sort order, and indicates the current sort state.
207      * @param $name internal name used for this type of sorting.
208      * @param $currentsort the current sort order -1, 0, 1 for descending, none, ascending.
209      * @param $title the link text.
210      * @param $defaultreverse whether the default sort order for this column is descending, rather than ascending.
211      * @return string HTML fragment.
212      */
213     protected function make_sort_link($sort, $title, $tip, $defaultreverse = false) {
214         $currentsort = $this->qbank->get_primary_sort_order($sort);
215         $newsortreverse = $defaultreverse;
216         if ($currentsort) {
217             $newsortreverse = $currentsort > 0;
218         }
219         if (!$tip) {
220             $tip = $title;
221         }
222         if ($newsortreverse) {
223             $tip = get_string('sortbyxreverse', '', $tip);
224         } else {
225             $tip = get_string('sortbyx', '', $tip);
226         }
227         $link = '<a href="' . $this->qbank->new_sort_url($sort, $newsortreverse) . '" title="' . $tip . '">';
228         $link .= $title;
229         if ($currentsort) {
230             $link .= $this->get_sort_icon($currentsort < 0);
231         }
232         $link .= '</a>';
233         return $link;
234     }
236     /**
237      * Get an icon representing the corrent sort state.
238      * @param $reverse sort is descending, not ascending.
239      * @return string HTML image tag.
240      */
241     protected function get_sort_icon($reverse) {
242         global $OUTPUT;
243         if ($reverse) {
244             return ' <img src="' . $OUTPUT->pix_url('t/up') . '" alt="' . get_string('desc') . '" />';
245         } else {
246             return ' <img src="' . $OUTPUT->pix_url('t/down') . '" alt="' . get_string('asc') . '" />';
247         }
248     }
250     /**
251      * Output this column.
252      * @param object $question the row from the $question table, augmented with extra information.
253      * @param string $rowclasses CSS class names that should be applied to this row of output.
254      */
255     public function display($question, $rowclasses) {
256         $this->display_start($question, $rowclasses);
257         $this->display_content($question, $rowclasses);
258         $this->display_end($question, $rowclasses);
259     }
261     protected function display_start($question, $rowclasses) {
262         echo '<td class="' . $this->get_classes() . '">';
263     }
265     /**
266      * @return string the CSS classes to apply to every cell in this column.
267      */
268     protected function get_classes() {
269         $classes = $this->get_extra_classes();
270         $classes[] = $this->get_name();
271         return implode(' ', $classes);
272     }
274     /**
275      * @param object $question the row from the $question table, augmented with extra information.
276      * @return string internal name for this column. Used as a CSS class name,
277      *     and to store information about the current sort. Must match PARAM_ALPHA.
278      */
279     public abstract function get_name();
281     /**
282      * @return array any extra class names you would like applied to every cell in this column.
283      */
284     public function get_extra_classes() {
285         return array();
286     }
288     /**
289      * Output the contents of this column.
290      * @param object $question the row from the $question table, augmented with extra information.
291      * @param string $rowclasses CSS class names that should be applied to this row of output.
292      */
293     protected abstract function display_content($question, $rowclasses);
295     protected function display_end($question, $rowclasses) {
296         echo "</td>\n";
297     }
299     /**
300      * Return an array 'table_alias' => 'JOIN clause' to bring in any data that
301      * this column required.
302      *
303      * The return values for all the columns will be checked. It is OK if two
304      * columns join in the same table with the same alias and identical JOIN clauses.
305      * If to columns try to use the same alias with different joins, you get an error.
306      * The only table included by default is the question table, which is aliased to 'q'.
307      *
308      * It is importnat that your join simply adds additional data (or NULLs) to the
309      * existing rows of the query. It must not cause additional rows.
310      *
311      * @return array 'table_alias' => 'JOIN clause'
312      */
313     public function get_extra_joins() {
314         return array();
315     }
317     /**
318      * @return array fields required. use table alias 'q' for the question table, or one of the
319      * ones from get_extra_joins. Every field requested must specify a table prefix.
320      */
321     public function get_required_fields() {
322         return array();
323     }
325     /**
326      * Can this column be sorted on? You can return either:
327      *  + false for no (the default),
328      *  + a field name, if sorting this column corresponds to sorting on that datbase field.
329      *  + an array of subnames to sort on as follows
330      *  return array(
331      *      'firstname' => array('field' => 'uc.firstname', 'title' => get_string('firstname')),
332      *      'lastname' => array('field' => 'uc.lastname', 'field' => get_string('lastname')),
333      *  );
334      * As well as field, and field, you can also add 'revers' => 1 if you want the default sort
335      * order to be DESC.
336      * @return mixed as above.
337      */
338     public function is_sortable() {
339         return false;
340     }
342     /**
343      * Helper method for building sort clauses.
344      * @param bool $reverse whether the normal direction should be reversed.
345      * @param string $normaldir 'ASC' or 'DESC'
346      * @return string 'ASC' or 'DESC'
347      */
348     protected function sortorder($reverse) {
349         if ($reverse) {
350             return ' DESC';
351         } else {
352             return ' ASC';
353         }
354     }
356     /**
357      * @param $reverse Whether to sort in the reverse of the default sort order.
358      * @param $subsort if is_sortable returns an array of subnames, then this will be
359      *      one of those. Otherwise will be empty.
360      * @return string some SQL to go in the order by clause.
361      */
362     public function sort_expression($reverse, $subsort) {
363         $sortable = $this->is_sortable();
364         if (is_array($sortable)) {
365             if (array_key_exists($subsort, $sortable)) {
366                 return $sortable[$subsort]['field'] . $this->sortorder($reverse, !empty($sortable[$subsort]['reverse']));
367             } else {
368                 throw new coding_exception('Unexpected $subsort type: ' . $subsort);
369             }
370         } else if ($sortable) {
371             return $sortable . $this->sortorder($reverse);
372         } else {
373             throw new coding_exception('sort_expression called on a non-sortable column.');
374         }
375     }
379 /**
380  * A column with a checkbox for each question with name q{questionid}.
381  *
382  * @copyright  2009 Tim Hunt
383  * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
384  */
385 class question_bank_checkbox_column extends question_bank_column_base {
386     protected $strselect;
387     protected $firstrow = true;
389     public function init() {
390         $this->strselect = get_string('select');
391     }
393     public function get_name() {
394         return 'checkbox';
395     }
397     protected function get_title() {
398         return '<input type="checkbox" disabled="disabled" id="qbheadercheckbox" />';
399     }
401     protected function get_title_tip() {
402         return get_string('selectquestionsforbulk', 'question');
403     }
405     protected function display_content($question, $rowclasses) {
406         global $PAGE;
407         echo '<input title="' . $this->strselect . '" type="checkbox" name="q' .
408                 $question->id . '" id="checkq' . $question->id . '" value="1"/>';
409         if ($this->firstrow) {
410             $PAGE->requires->js_function_call('question_bank.init_checkbox_column', array(get_string('selectall'),
411                     get_string('deselectall'), 'checkq' . $question->id));
412             $this->firstrow = false;
413         }
414     }
416     public function get_required_fields() {
417         return array('q.id');
418     }
422 /**
423  * A column type for the name of the question type.
424  *
425  * @copyright  2009 Tim Hunt
426  * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
427  */
428 class question_bank_question_type_column extends question_bank_column_base {
429     public function get_name() {
430         return 'qtype';
431     }
433     protected function get_title() {
434         return get_string('qtypeveryshort', 'question');
435     }
437     protected function get_title_tip() {
438         return get_string('questiontype', 'question');
439     }
441     protected function display_content($question, $rowclasses) {
442         echo print_question_icon($question);
443     }
445     public function get_required_fields() {
446         return array('q.qtype');
447     }
449     public function is_sortable() {
450         return 'q.qtype';
451     }
455 /**
456  * A column type for the name of the question name.
457  *
458  * @copyright  2009 Tim Hunt
459  * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
460  */
461 class question_bank_question_name_column extends question_bank_column_base {
462     protected $checkboxespresent = null;
464     public function get_name() {
465         return 'questionname';
466     }
468     protected function get_title() {
469         return get_string('question');
470     }
472     protected function label_for($question) {
473         if (is_null($this->checkboxespresent)) {
474             $this->checkboxespresent = $this->qbank->has_column('checkbox');
475         }
476         if ($this->checkboxespresent) {
477             return 'checkq' . $question->id;
478         } else {
479             return '';
480         }
481     }
483     protected function display_content($question, $rowclasses) {
484         $labelfor = $this->label_for($question);
485         if ($labelfor) {
486             echo '<label for="' . $labelfor . '">';
487         }
488         echo format_string($question->name);
489         if ($labelfor) {
490             echo '</label>';
491         }
492     }
494     public function get_required_fields() {
495         return array('q.id', 'q.name');
496     }
498     public function is_sortable() {
499         return 'q.name';
500     }
504 /**
505  * A column type for the name of the question creator.
506  *
507  * @copyright  2009 Tim Hunt
508  * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
509  */
510 class question_bank_creator_name_column extends question_bank_column_base {
511     public function get_name() {
512         return 'creatorname';
513     }
515     protected function get_title() {
516         return get_string('createdby', 'question');
517     }
519     protected function display_content($question, $rowclasses) {
520         if (!empty($question->creatorfirstname) && !empty($question->creatorlastname)) {
521             $u = new stdClass();
522             $u->firstname = $question->creatorfirstname;
523             $u->lastname = $question->creatorlastname;
524             echo fullname($u);
525         }
526     }
528     public function get_extra_joins() {
529         return array('uc' => 'LEFT JOIN {user} uc ON uc.id = q.createdby');
530     }
532     public function get_required_fields() {
533         return array('uc.firstname AS creatorfirstname', 'uc.lastname AS creatorlastname');
534     }
536     public function is_sortable() {
537         return array(
538             'firstname' => array('field' => 'uc.firstname', 'title' => get_string('firstname')),
539             'lastname' => array('field' => 'uc.lastname', 'title' => get_string('lastname')),
540         );
541     }
545 /**
546  * A column type for the name of the question last modifier.
547  *
548  * @copyright  2009 Tim Hunt
549  * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
550  */
551 class question_bank_modifier_name_column extends question_bank_column_base {
552     public function get_name() {
553         return 'modifiername';
554     }
556     protected function get_title() {
557         return get_string('lastmodifiedby', 'question');
558     }
560     protected function display_content($question, $rowclasses) {
561         if (!empty($question->modifierfirstname) && !empty($question->modifierlastname)) {
562             $u = new stdClass();
563             $u->firstname = $question->modifierfirstname;
564             $u->lastname = $question->modifierlastname;
565             echo fullname($u);
566         }
567     }
569     public function get_extra_joins() {
570         return array('um' => 'LEFT JOIN {user} um ON um.id = q.modifiedby');
571     }
573     public function get_required_fields() {
574         return array('um.firstname AS modifierfirstname', 'um.lastname AS modifierlastname');
575     }
577     public function is_sortable() {
578         return array(
579             'firstname' => array('field' => 'um.firstname', 'title' => get_string('firstname')),
580             'lastname' => array('field' => 'um.lastname', 'title' => get_string('lastname')),
581         );
582     }
586 /**
587  * A base class for actions that are an icon that lets you manipulate the question in some way.
588  *
589  * @copyright  2009 Tim Hunt
590  * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
591  */
592 abstract class question_bank_action_column_base extends question_bank_column_base {
594     protected function get_title() {
595         return '&#160;';
596     }
598     public function get_extra_classes() {
599         return array('iconcol');
600     }
602     protected function print_icon($icon, $title, $url) {
603         global $OUTPUT;
604         echo '<a title="' . $title . '" href="' . $url . '">
605                 <img src="' . $OUTPUT->pix_url($icon) . '" class="iconsmall" alt="' . $title . '" /></a>';
606     }
608     public function get_required_fields() {
609         return array('q.id');
610     }
614 /**
615  * Base class for question bank columns that just contain an action icon.
616  *
617  * @copyright  2009 Tim Hunt
618  * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
619  */
620 class question_bank_edit_action_column extends question_bank_action_column_base {
621     protected $stredit;
622     protected $strview;
624     public function init() {
625         parent::init();
626         $this->stredit = get_string('edit');
627         $this->strview = get_string('view');
628     }
630     public function get_name() {
631         return 'editaction';
632     }
634     protected function display_content($question, $rowclasses) {
635         if (question_has_capability_on($question, 'edit') ||
636                 question_has_capability_on($question, 'move')) {
637             $this->print_icon('t/edit', $this->stredit, $this->qbank->edit_question_url($question->id));
638         } else {
639             $this->print_icon('i/info', $this->strview, $this->qbank->edit_question_url($question->id));
640         }
641     }
645 /**
646  * Question bank columns for the preview action icon.
647  *
648  * @copyright  2009 Tim Hunt
649  * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
650  */
651 class question_bank_preview_action_column extends question_bank_action_column_base {
652     protected $strpreview;
654     public function init() {
655         parent::init();
656         $this->strpreview = get_string('preview');
657     }
659     public function get_name() {
660         return 'previewaction';
661     }
663     protected function display_content($question, $rowclasses) {
664         global $OUTPUT;
665         if (question_has_capability_on($question, 'use')) {
666             // Build the icon.
667             $image = $OUTPUT->pix_icon('t/preview', $this->strpreview);
669             $link = $this->qbank->preview_question_url($question);
670             $action = new popup_action('click', $link, 'questionpreview',
671                     question_preview_popup_params());
673             echo $OUTPUT->action_link($link, $image, $action, array('title' => $this->strpreview));
674         }
675     }
677     public function get_required_fields() {
678         return array('q.id');
679     }
683 /**
684  * Question bank columns for the move action icon.
685  *
686  * @copyright  2009 Tim Hunt
687  * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
688  */
689 class question_bank_move_action_column extends question_bank_action_column_base {
690     protected $strmove;
692     public function init() {
693         parent::init();
694         $this->strmove = get_string('move');
695     }
697     public function get_name() {
698         return 'moveaction';
699     }
701     protected function display_content($question, $rowclasses) {
702         if (question_has_capability_on($question, 'move')) {
703             $this->print_icon('t/move', $this->strmove, $this->qbank->move_question_url($question->id));
704         }
705     }
709 /**
710  * action to delete (or hide) a question, or restore a previously hidden question.
711  *
712  * @copyright  2009 Tim Hunt
713  * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
714  */
715 class question_bank_delete_action_column extends question_bank_action_column_base {
716     protected $strdelete;
717     protected $strrestore;
719     public function init() {
720         parent::init();
721         $this->strdelete = get_string('delete');
722         $this->strrestore = get_string('restore');
723     }
725     public function get_name() {
726         return 'deleteaction';
727     }
729     protected function display_content($question, $rowclasses) {
730         if (question_has_capability_on($question, 'edit')) {
731             if ($question->hidden) {
732                 $url = new moodle_url($this->qbank->base_url(), array('unhide' => $question->id, 'sesskey'=>sesskey()));
733                 $this->print_icon('t/restore', $this->strrestore, $url);
734             } else {
735                 $url = new moodle_url($this->qbank->base_url(), array('deleteselected' => $question->id, 'q' . $question->id => 1, 'sesskey'=>sesskey()));
736                 $this->print_icon('t/delete', $this->strdelete, $url);
737             }
738         }
739     }
741     public function get_required_fields() {
742         return array('q.id', 'q.hidden');
743     }
746 /**
747  * Base class for 'columns' that are actually displayed as a row following the main question row.
748  *
749  * @copyright  2009 Tim Hunt
750  * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
751  */
752 abstract class question_bank_row_base extends question_bank_column_base {
753     public function is_extra_row() {
754         return true;
755     }
757     protected function display_start($question, $rowclasses) {
758         if ($rowclasses) {
759             echo '<tr class="' . $rowclasses . '">' . "\n";
760         } else {
761             echo "<tr>\n";
762         }
763         echo '<td colspan="' . $this->qbank->get_column_count() . '" class="' . $this->get_name() . '">';
764     }
766     protected function display_end($question, $rowclasses) {
767         echo "</td></tr>\n";
768     }
771 /**
772  * A column type for the name of the question name.
773  *
774  * @copyright  2009 Tim Hunt
775  * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
776  */
777 class question_bank_question_text_row extends question_bank_row_base {
778     protected $formatoptions;
780     protected function init() {
781         $this->formatoptions = new stdClass();
782         $this->formatoptions->noclean = true;
783         $this->formatoptions->para = false;
784     }
786     public function get_name() {
787         return 'questiontext';
788     }
790     protected function get_title() {
791         return get_string('questiontext', 'question');
792     }
794     protected function display_content($question, $rowclasses) {
795         $text = question_rewrite_questiontext_preview_urls($question->questiontext,
796                 $question->contextid, 'question', $question->id);
797         $text = format_text($text, $question->questiontextformat,
798                 $this->formatoptions);
799         if ($text == '') {
800             $text = '&#160;';
801         }
802         echo $text;
803     }
805     public function get_extra_joins() {
806         return array('qc' => 'JOIN {question_categories} qc ON qc.id = q.category');
807     }
809     public function get_required_fields() {
810         return array('q.id', 'q.questiontext', 'q.questiontextformat', 'qc.contextid');
811     }
814 /**
815  * This class prints a view of the question bank, including
816  *  + Some controls to allow users to to select what is displayed.
817  *  + A list of questions as a table.
818  *  + Further controls to do things with the questions.
819  *
820  * This class gives a basic view, and provides plenty of hooks where subclasses
821  * can override parts of the display.
822  *
823  * The list of questions presented as a table is generated by creating a list of
824  * question_bank_column objects, one for each 'column' to be displayed. These
825  * manage
826  *  + outputting the contents of that column, given a $question object, but also
827  *  + generating the right fragments of SQL to ensure the necessary data is present,
828  *    and sorted in the right order.
829  *  + outputting table headers.
830  *
831  * @copyright  2009 Tim Hunt
832  * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
833  */
834 class question_bank_view {
835     const MAX_SORTS = 3;
837     protected $baseurl;
838     protected $editquestionurl;
839     protected $quizorcourseid;
840     protected $contexts;
841     protected $cm;
842     protected $course;
843     protected $knowncolumntypes;
844     protected $visiblecolumns;
845     protected $extrarows;
846     protected $requiredcolumns;
847     protected $sort;
848     protected $lastchangedid;
849     protected $countsql;
850     protected $loadsql;
851     protected $sqlparams;
853     /**
854      * Constructor
855      * @param question_edit_contexts $contexts
856      * @param moodle_url $pageurl
857      * @param object $course course settings
858      * @param object $cm (optional) activity settings.
859      */
860     public function __construct($contexts, $pageurl, $course, $cm = null) {
861         global $CFG, $PAGE;
863         $this->contexts = $contexts;
864         $this->baseurl = $pageurl;
865         $this->course = $course;
866         $this->cm = $cm;
868         if (!empty($cm) && $cm->modname == 'quiz') {
869             $this->quizorcourseid = '&amp;quizid=' . $cm->instance;
870         } else {
871             $this->quizorcourseid = '&amp;courseid=' .$this->course->id;
872         }
874         // Create the url of the new question page to forward to.
875         $returnurl = $pageurl->out_as_local_url(false);
876         $this->editquestionurl = new moodle_url('/question/question.php',
877                 array('returnurl' => $returnurl));
878         if ($cm !== null){
879             $this->editquestionurl->param('cmid', $cm->id);
880         } else {
881             $this->editquestionurl->param('courseid', $this->course->id);
882         }
884         $this->lastchangedid = optional_param('lastchanged',0,PARAM_INT);
886         $this->init_column_types();
887         $this->init_columns($this->wanted_columns());
888         $this->init_sort();
890         $PAGE->requires->yui2_lib('container');
891     }
893     protected function wanted_columns() {
894         $columns = array('checkbox', 'qtype', 'questionname', 'editaction',
895                 'previewaction', 'moveaction', 'deleteaction', 'creatorname',
896                 'modifiername');
897         if (optional_param('qbshowtext', false, PARAM_BOOL)) {
898             $columns[] = 'questiontext';
899         }
900         return $columns;
901     }
903     protected function known_field_types() {
904         return array(
905             new question_bank_checkbox_column($this),
906             new question_bank_question_type_column($this),
907             new question_bank_question_name_column($this),
908             new question_bank_creator_name_column($this),
909             new question_bank_modifier_name_column($this),
910             new question_bank_edit_action_column($this),
911             new question_bank_preview_action_column($this),
912             new question_bank_move_action_column($this),
913             new question_bank_delete_action_column($this),
914             new question_bank_question_text_row($this),
915         );
916     }
918     protected function init_column_types() {
919         $this->knowncolumntypes = array();
920         foreach ($this->known_field_types() as $col) {
921             $this->knowncolumntypes[$col->get_name()] = $col;
922         }
923     }
925     protected function init_columns($wanted) {
926         $this->visiblecolumns = array();
927         $this->extrarows = array();
928         foreach ($wanted as $colname) {
929             if (!isset($this->knowncolumntypes[$colname])) {
930                 throw new coding_exception('Unknown column type ' . $colname . ' requested in init columns.');
931             }
932             $column = $this->knowncolumntypes[$colname];
933             if ($column->is_extra_row()) {
934                 $this->extrarows[$colname] = $column;
935             } else {
936                 $this->visiblecolumns[$colname] = $column;
937             }
938         }
939         $this->requiredcolumns = array_merge($this->visiblecolumns, $this->extrarows);
940     }
942     /**
943      * @param string $colname a column internal name.
944      * @return bool is this column included in the output?
945      */
946     public function has_column($colname) {
947         return isset($this->visiblecolumns[$colname]);
948     }
950     /**
951      * @return int The number of columns in the table.
952      */
953     public function get_column_count() {
954         return count($this->visiblecolumns);
955     }
957     public function get_courseid() {
958         return $this->course->id;
959     }
961     protected function init_sort() {
962         $this->init_sort_from_params();
963         if (empty($this->sort)) {
964             $this->sort = $this->default_sort();
965         }
966     }
968     /**
969      * Deal with a sort name of the form columnname, or colname_subsort by
970      * breaking it up, validating the bits that are presend, and returning them.
971      * If there is no subsort, then $subsort is returned as ''.
972      * @return array array($colname, $subsort).
973      */
974     protected function parse_subsort($sort) {
975     /// Do the parsing.
976         if (strpos($sort, '_') !== false) {
977             list($colname, $subsort) = explode('_', $sort, 2);
978         } else {
979             $colname = $sort;
980             $subsort = '';
981         }
982     /// Validate the column name.
983         if (!isset($this->knowncolumntypes[$colname]) || !$this->knowncolumntypes[$colname]->is_sortable()) {
984             for ($i = 1; $i <= question_bank_view::MAX_SORTS; $i++) {
985                 $this->baseurl->remove_params('qbs' . $i);
986             }
987             throw new moodle_exception('unknownsortcolumn', '', $link = $this->baseurl->out(), $colname);
988         }
989     /// Validate the subsort, if present.
990         if ($subsort) {
991             $subsorts = $this->knowncolumntypes[$colname]->is_sortable();
992             if (!is_array($subsorts) || !isset($subsorts[$subsort])) {
993                 throw new moodle_exception('unknownsortcolumn', '', $link = $this->baseurl->out(), $sort);
994             }
995         }
996         return array($colname, $subsort);
997     }
999     protected function init_sort_from_params() {
1000         $this->sort = array();
1001         for ($i = 1; $i <= question_bank_view::MAX_SORTS; $i++) {
1002             if (!$sort = optional_param('qbs' . $i, '', PARAM_ALPHAEXT)) {
1003                 break;
1004             }
1005             // Work out the appropriate order.
1006             $order = 1;
1007             if ($sort[0] == '-') {
1008                 $order = -1;
1009                 $sort = substr($sort, 1);
1010                 if (!$sort) {
1011                     break;
1012                 }
1013             }
1014             // Deal with subsorts.
1015             list($colname, $subsort) = $this->parse_subsort($sort);
1016             $this->requiredcolumns[$colname] = $this->knowncolumntypes[$colname];
1017             $this->sort[$sort] = $order;
1018         }
1019     }
1021     protected function sort_to_params($sorts) {
1022         $params = array();
1023         $i = 0;
1024         foreach ($sorts as $sort => $order) {
1025             $i += 1;
1026             if ($order < 0) {
1027                 $sort = '-' . $sort;
1028             }
1029             $params['qbs' . $i] = $sort;
1030         }
1031         return $params;
1032     }
1034     protected function default_sort() {
1035         return array('qtype' => 1, 'questionname' => 1);
1036     }
1038     /**
1039      * @param $sort a column or column_subsort name.
1040      * @return int the current sort order for this column -1, 0, 1
1041      */
1042     public function get_primary_sort_order($sort) {
1043         $order = reset($this->sort);
1044         $primarysort = key($this->sort);
1045         if ($sort == $primarysort) {
1046             return $order;
1047         } else {
1048             return 0;
1049         }
1050     }
1052     /**
1053      * Get a URL to redisplay the page with a new sort for the question bank.
1054      * @param string $sort the column, or column_subsort to sort on.
1055      * @param bool $newsortreverse whether to sort in reverse order.
1056      * @return string The new URL.
1057      */
1058     public function new_sort_url($sort, $newsortreverse) {
1059         if ($newsortreverse) {
1060             $order = -1;
1061         } else {
1062             $order = 1;
1063         }
1064         // Tricky code to add the new sort at the start, removing it from where it was before, if it was present.
1065         $newsort = array_reverse($this->sort);
1066         if (isset($newsort[$sort])) {
1067             unset($newsort[$sort]);
1068         }
1069         $newsort[$sort] = $order;
1070         $newsort = array_reverse($newsort);
1071         if (count($newsort) > question_bank_view::MAX_SORTS) {
1072             $newsort = array_slice($newsort, 0, question_bank_view::MAX_SORTS, true);
1073         }
1074         return $this->baseurl->out(true, $this->sort_to_params($newsort));
1075     }
1077     protected function build_query_sql($category, $recurse, $showhidden) {
1078         global $DB;
1080     /// Get the required tables.
1081         $joins = array();
1082         foreach ($this->requiredcolumns as $column) {
1083             $extrajoins = $column->get_extra_joins();
1084             foreach ($extrajoins as $prefix => $join) {
1085                 if (isset($joins[$prefix]) && $joins[$prefix] != $join) {
1086                     throw new coding_exception('Join ' . $join . ' conflicts with previous join ' . $joins[$prefix]);
1087                 }
1088                 $joins[$prefix] = $join;
1089             }
1090         }
1092     /// Get the required fields.
1093         $fields = array('q.hidden', 'q.category');
1094         foreach ($this->visiblecolumns as $column) {
1095             $fields = array_merge($fields, $column->get_required_fields());
1096         }
1097         foreach ($this->extrarows as $row) {
1098             $fields = array_merge($fields, $row->get_required_fields());
1099         }
1100         $fields = array_unique($fields);
1102     /// Build the order by clause.
1103         $sorts = array();
1104         foreach ($this->sort as $sort => $order) {
1105             list($colname, $subsort) = $this->parse_subsort($sort);
1106             $sorts[] = $this->requiredcolumns[$colname]->sort_expression($order < 0, $subsort);
1107         }
1109     /// Build the where clause.
1110         $tests = array('q.parent = 0');
1112         if (!$showhidden) {
1113             $tests[] = 'q.hidden = 0';
1114         }
1116         if ($recurse) {
1117             $categoryids = question_categorylist($category->id);
1118         } else {
1119             $categoryids = array($category->id);
1120         }
1121         list($catidtest, $params) = $DB->get_in_or_equal($categoryids, SQL_PARAMS_NAMED, 'cat');
1122         $tests[] = 'q.category ' . $catidtest;
1123         $this->sqlparams = $params;
1125     /// Build the SQL.
1126         $sql = ' FROM {question} q ' . implode(' ', $joins);
1127         $sql .= ' WHERE ' . implode(' AND ', $tests);
1128         $this->countsql = 'SELECT count(1)' . $sql;
1129         $this->loadsql = 'SELECT ' . implode(', ', $fields) . $sql . ' ORDER BY ' . implode(', ', $sorts);
1130         $this->sqlparams = $params;
1131     }
1133     protected function get_question_count() {
1134         global $DB;
1135         return $DB->count_records_sql($this->countsql, $this->sqlparams);
1136     }
1138     protected function load_page_questions($page, $perpage) {
1139         global $DB;
1140         $questions = $DB->get_recordset_sql($this->loadsql, $this->sqlparams, $page*$perpage, $perpage);
1141         if (!$questions->valid()) {
1142         /// No questions on this page. Reset to page 0.
1143             $questions = $DB->get_recordset_sql($this->loadsql, $this->sqlparams, 0, $perpage);
1144         }
1145         return $questions;
1146     }
1148     public function base_url() {
1149         return $this->baseurl;
1150     }
1152     public function edit_question_url($questionid) {
1153         return $this->editquestionurl->out(true, array('id' => $questionid));
1154     }
1156     public function move_question_url($questionid) {
1157         return $this->editquestionurl->out(true, array('id' => $questionid, 'movecontext' => 1));
1158     }
1160     public function preview_question_url($question) {
1161         return question_preview_url($question->id, null, null, null, null,
1162                 $this->contexts->lowest());
1163     }
1165     /**
1166      * Shows the question bank editing interface.
1167      *
1168      * The function also processes a number of actions:
1169      *
1170      * Actions affecting the question pool:
1171      * move           Moves a question to a different category
1172      * deleteselected Deletes the selected questions from the category
1173      * Other actions:
1174      * category      Chooses the category
1175      * displayoptions Sets display options
1176      */
1177     public function display($tabname, $page, $perpage, $cat,
1178             $recurse, $showhidden, $showquestiontext) {
1179         global $PAGE, $OUTPUT;
1181         if ($this->process_actions_needing_ui()) {
1182             return;
1183         }
1185         $PAGE->requires->js('/question/qbank.js');
1187         // Category selection form
1188         echo $OUTPUT->heading(get_string('questionbank', 'question'), 2);
1190         $this->display_category_form($this->contexts->having_one_edit_tab_cap($tabname),
1191                 $this->baseurl, $cat);
1192         $this->display_options($recurse, $showhidden, $showquestiontext);
1194         if (!$category = $this->get_current_category($cat)) {
1195             return;
1196         }
1197         $this->print_category_info($category);
1199         // continues with list of questions
1200         $this->display_question_list($this->contexts->having_one_edit_tab_cap($tabname),
1201                 $this->baseurl, $cat, $this->cm,
1202                 $recurse, $page, $perpage, $showhidden, $showquestiontext,
1203                 $this->contexts->having_cap('moodle/question:add'));
1204     }
1206     protected function print_choose_category_message($categoryandcontext) {
1207         echo "<p style=\"text-align:center;\"><b>";
1208         print_string('selectcategoryabove', 'question');
1209         echo "</b></p>";
1210     }
1212     protected function get_current_category($categoryandcontext) {
1213         global $DB, $OUTPUT;
1214         list($categoryid, $contextid) = explode(',', $categoryandcontext);
1215         if (!$categoryid) {
1216             $this->print_choose_category_message($categoryandcontext);
1217             return false;
1218         }
1220         if (!$category = $DB->get_record('question_categories',
1221                 array('id' => $categoryid, 'contextid' => $contextid))) {
1222             echo $OUTPUT->box_start('generalbox questionbank');
1223             echo $OUTPUT->notification('Category not found!');
1224             echo $OUTPUT->box_end();
1225             return false;
1226         }
1228         return $category;
1229     }
1231     protected function print_category_info($category) {
1232         $formatoptions = new stdClass();
1233         $formatoptions->noclean = true;
1234         $formatoptions->overflowdiv = true;
1235         echo '<div class="boxaligncenter">';
1236         echo format_text($category->info, $category->infoformat, $formatoptions, $this->course->id);
1237         echo "</div>\n";
1238     }
1240     /**
1241      * prints a form to choose categories
1242      */
1243     protected function display_category_form($contexts, $pageurl, $current) {
1244         global $CFG, $OUTPUT;
1246     /// Get all the existing categories now
1247         echo '<div class="choosecategory">';
1248         $catmenu = question_category_options($contexts, false, 0, true);
1250         $select = new single_select($this->baseurl, 'category', $catmenu, $current, null, 'catmenu');
1251         $select->set_label(get_string('selectacategory', 'question'));
1252         echo $OUTPUT->render($select);
1253         echo "</div>\n";
1254     }
1256     protected function display_options($recurse, $showhidden, $showquestiontext) {
1257         echo '<form method="get" action="edit.php" id="displayoptions">';
1258         echo "<fieldset class='invisiblefieldset'>";
1259         echo html_writer::input_hidden_params($this->baseurl, array('recurse', 'showhidden', 'qbshowtext'));
1260         $this->display_category_form_checkbox('recurse', $recurse, get_string('includesubcategories', 'question'));
1261         $this->display_category_form_checkbox('showhidden', $showhidden, get_string('showhidden', 'question'));
1262         $this->display_category_form_checkbox('qbshowtext', $showquestiontext, get_string('showquestiontext', 'question'));
1263         echo '<noscript><div class="centerpara"><input type="submit" value="'. get_string('go') .'" />';
1264         echo '</div></noscript></fieldset></form>';
1265     }
1267     /**
1268      * Print a single option checkbox. Used by the preceeding.
1269      */
1270     protected function display_category_form_checkbox($name, $value, $label) {
1271         echo '<div><input type="hidden" id="' . $name . '_off" name="' . $name . '" value="0" />';
1272         echo '<input type="checkbox" id="' . $name . '_on" name="' . $name . '" value="1"';
1273         if ($value) {
1274             echo ' checked="checked"';
1275         }
1276         echo ' onchange="getElementById(\'displayoptions\').submit(); return true;" />';
1277         echo '<label for="' . $name . '_on">' . $label . '</label>';
1278         echo "</div>\n";
1279     }
1281     protected function create_new_question_form($category, $canadd) {
1282         global $CFG;
1283         echo '<div class="createnewquestion">';
1284         if ($canadd) {
1285             create_new_question_button($category->id, $this->editquestionurl->params(),
1286                     get_string('createnewquestion', 'question'));
1287         } else {
1288             print_string('nopermissionadd', 'question');
1289         }
1290         echo '</div>';
1291     }
1293     /**
1294     * Prints the table of questions in a category with interactions
1295     *
1296     * @param object $course   The course object
1297     * @param int $categoryid  The id of the question category to be displayed
1298     * @param int $cm      The course module record if we are in the context of a particular module, 0 otherwise
1299     * @param int $recurse     This is 1 if subcategories should be included, 0 otherwise
1300     * @param int $page        The number of the page to be displayed
1301     * @param int $perpage     Number of questions to show per page
1302     * @param bool $showhidden   True if also hidden questions should be displayed
1303     * @param bool $showquestiontext whether the text of each question should be shown in the list
1304     */
1305     protected function display_question_list($contexts, $pageurl, $categoryandcontext,
1306             $cm = null, $recurse=1, $page=0, $perpage=100, $showhidden=false,
1307             $showquestiontext = false, $addcontexts = array()) {
1308         global $CFG, $DB, $OUTPUT;
1310         $category = $this->get_current_category($categoryandcontext);
1312         $cmoptions = new stdClass();
1313         $cmoptions->hasattempts = !empty($this->quizhasattempts);
1315         $strselectall = get_string('selectall');
1316         $strselectnone = get_string('deselectall');
1317         $strdelete = get_string('delete');
1319         list($categoryid, $contextid) = explode(',', $categoryandcontext);
1320         $catcontext = get_context_instance_by_id($contextid);
1322         $canadd = has_capability('moodle/question:add', $catcontext);
1323         $caneditall =has_capability('moodle/question:editall', $catcontext);
1324         $canuseall =has_capability('moodle/question:useall', $catcontext);
1325         $canmoveall =has_capability('moodle/question:moveall', $catcontext);
1327         $this->create_new_question_form($category, $canadd);
1329         $this->build_query_sql($category, $recurse, $showhidden);
1330         $totalnumber = $this->get_question_count();
1331         if ($totalnumber == 0) {
1332             return;
1333         }
1335         $questions = $this->load_page_questions($page, $perpage);
1337         echo '<div class="categorypagingbarcontainer">';
1338         $pageing_url = new moodle_url('edit.php');
1339         $r = $pageing_url->params($pageurl->params());
1340         $pagingbar = new paging_bar($totalnumber, $page, $perpage, $pageing_url);
1341         $pagingbar->pagevar = 'qpage';
1342         echo $OUTPUT->render($pagingbar);
1343         echo '</div>';
1345         echo '<form method="post" action="edit.php">';
1346         echo '<fieldset class="invisiblefieldset" style="display: block;">';
1347         echo '<input type="hidden" name="sesskey" value="'.sesskey().'" />';
1348         echo html_writer::input_hidden_params($pageurl);
1350         echo '<div class="categoryquestionscontainer">';
1351         $this->start_table();
1352         $rowcount = 0;
1353         foreach ($questions as $question) {
1354             $this->print_table_row($question, $rowcount);
1355             $rowcount += 1;
1356         }
1357         $this->end_table();
1358         echo "</div>\n";
1360         echo '<div class="categorypagingbarcontainer pagingbottom">';
1361         echo $OUTPUT->render($pagingbar);
1362         if ($totalnumber > DEFAULT_QUESTIONS_PER_PAGE) {
1363             if ($perpage == DEFAULT_QUESTIONS_PER_PAGE) {
1364                 $url = new moodle_url('edit.php', array_merge($pageurl->params(), array('qperpage'=>1000)));
1365                 $showall = '<a href="'.$url.'">'.get_string('showall', 'moodle', $totalnumber).'</a>';
1366             } else {
1367                 $url = new moodle_url('edit.php', array_merge($pageurl->params(), array('qperpage'=>DEFAULT_QUESTIONS_PER_PAGE)));
1368                 $showall = '<a href="'.$url.'">'.get_string('showperpage', 'moodle', DEFAULT_QUESTIONS_PER_PAGE).'</a>';
1369             }
1370             echo "<div class='paging'>$showall</div>";
1371         }
1372         echo '</div>';
1374         echo '<div class="modulespecificbuttonscontainer">';
1375         if ($caneditall || $canmoveall || $canuseall){
1376             echo '<strong>&nbsp;'.get_string('withselected', 'question').':</strong><br />';
1378             if (function_exists('module_specific_buttons')) {
1379                 echo module_specific_buttons($this->cm->id,$cmoptions);
1380             }
1382             // print delete and move selected question
1383             if ($caneditall) {
1384                 echo '<input type="submit" name="deleteselected" value="' . $strdelete . "\" />\n";
1385             }
1387             if ($canmoveall && count($addcontexts)) {
1388                 echo '<input type="submit" name="move" value="'.get_string('moveto', 'question')."\" />\n";
1389                 question_category_select_menu($addcontexts, false, 0, "$category->id,$category->contextid");
1390             }
1392             if (function_exists('module_specific_controls') && $canuseall) {
1393                 $modulespecific = module_specific_controls($totalnumber, $recurse, $category, $this->cm->id,$cmoptions);
1394                 if(!empty($modulespecific)){
1395                     echo "<hr />$modulespecific";
1396                 }
1397             }
1398         }
1399         echo "</div>\n";
1401         echo '</fieldset>';
1402         echo "</form>\n";
1403     }
1405     protected function start_table() {
1406         echo '<table id="categoryquestions">' . "\n";
1407         echo "<thead>\n";
1408         $this->print_table_headers();
1409         echo "</thead>\n";
1410         echo "<tbody>\n";
1411     }
1413     protected function end_table() {
1414         echo "</tbody>\n";
1415         echo "</table>\n";
1416     }
1418     protected function print_table_headers() {
1419         echo "<tr>\n";
1420         foreach ($this->visiblecolumns as $column) {
1421             $column->display_header();
1422         }
1423         echo "</tr>\n";
1424     }
1426     protected function get_row_classes($question, $rowcount) {
1427         $classes = array();
1428         if ($question->hidden) {
1429             $classes[] = 'dimmed_text';
1430         }
1431         if ($question->id == $this->lastchangedid) {
1432             $classes[] ='highlight';
1433         }
1434         $classes[] = 'r' . ($rowcount % 2);
1435         return $classes;
1436     }
1438     protected function print_table_row($question, $rowcount) {
1439         $rowclasses = implode(' ', $this->get_row_classes($question, $rowcount));
1440         if ($rowclasses) {
1441             echo '<tr class="' . $rowclasses . '">' . "\n";
1442         } else {
1443             echo "<tr>\n";
1444         }
1445         foreach ($this->visiblecolumns as $column) {
1446             $column->display($question, $rowclasses);
1447         }
1448         echo "</tr>\n";
1449         foreach ($this->extrarows as $row) {
1450             $row->display($question, $rowclasses);
1451         }
1452     }
1454     public function process_actions() {
1455         global $CFG, $DB;
1456         /// Now, check for commands on this page and modify variables as necessary
1457         if (optional_param('move', false, PARAM_BOOL) and confirm_sesskey()) {
1458             // Move selected questions to new category
1459             $category = required_param('category', PARAM_SEQUENCE);
1460             list($tocategoryid, $contextid) = explode(',', $category);
1461             if (! $tocategory = $DB->get_record('question_categories', array('id' => $tocategoryid, 'contextid' => $contextid))) {
1462                 print_error('cannotfindcate', 'question');
1463             }
1464             $tocontext = get_context_instance_by_id($contextid);
1465             require_capability('moodle/question:add', $tocontext);
1466             $rawdata = (array) data_submitted();
1467             $questionids = array();
1468             foreach ($rawdata as $key => $value) {    // Parse input for question ids
1469                 if (preg_match('!^q([0-9]+)$!', $key, $matches)) {
1470                     $key = $matches[1];
1471                     $questionids[] = $key;
1472                 }
1473             }
1474             if ($questionids) {
1475                 list($usql, $params) = $DB->get_in_or_equal($questionids);
1476                 $sql = "";
1477                 $questions = $DB->get_records_sql("
1478                         SELECT q.*, c.contextid
1479                         FROM {question} q
1480                         JOIN {question_categories} c ON c.id = q.category
1481                         WHERE q.id $usql", $params);
1482                 foreach ($questions as $question){
1483                     question_require_capability_on($question, 'move');
1484                 }
1485                 question_move_questions_to_category($questionids, $tocategory->id);
1486                 redirect($this->baseurl->out(false,
1487                         array('category' => "$tocategoryid,$contextid")));
1488             }
1489         }
1491         if (optional_param('deleteselected', false, PARAM_BOOL)) { // delete selected questions from the category
1492             if (($confirm = optional_param('confirm', '', PARAM_ALPHANUM)) and confirm_sesskey()) { // teacher has already confirmed the action
1493                 $deleteselected = required_param('deleteselected', PARAM_RAW);
1494                 if ($confirm == md5($deleteselected)) {
1495                     if ($questionlist = explode(',', $deleteselected)) {
1496                         // for each question either hide it if it is in use or delete it
1497                         foreach ($questionlist as $questionid) {
1498                             $questionid = (int)$questionid;
1499                             question_require_capability_on($questionid, 'edit');
1500                             if (questions_in_use(array($questionid))) {
1501                                 $DB->set_field('question', 'hidden', 1, array('id' => $questionid));
1502                             } else {
1503                                 question_delete_question($questionid);
1504                             }
1505                         }
1506                     }
1507                     redirect($this->baseurl);
1508                 } else {
1509                     print_error('invalidconfirm', 'question');
1510                 }
1511             }
1512         }
1514         // Unhide a question
1515         if(($unhide = optional_param('unhide', '', PARAM_INT)) and confirm_sesskey()) {
1516             question_require_capability_on($unhide, 'edit');
1517             $DB->set_field('question', 'hidden', 0, array('id' => $unhide));
1518             redirect($this->baseurl);
1519         }
1520     }
1522     public function process_actions_needing_ui() {
1523         global $DB, $OUTPUT;
1524         if (optional_param('deleteselected', false, PARAM_BOOL)) {
1525             // make a list of all the questions that are selected
1526             $rawquestions = $_REQUEST; // This code is called by both POST forms and GET links, so cannot use data_submitted.
1527             $questionlist = '';  // comma separated list of ids of questions to be deleted
1528             $questionnames = ''; // string with names of questions separated by <br /> with
1529                                  // an asterix in front of those that are in use
1530             $inuse = false;      // set to true if at least one of the questions is in use
1531             foreach ($rawquestions as $key => $value) {    // Parse input for question ids
1532                 if (preg_match('!^q([0-9]+)$!', $key, $matches)) {
1533                     $key = $matches[1];
1534                     $questionlist .= $key.',';
1535                     question_require_capability_on($key, 'edit');
1536                     if (questions_in_use(array($key))) {
1537                         $questionnames .= '* ';
1538                         $inuse = true;
1539                     }
1540                     $questionnames .= $DB->get_field('question', 'name', array('id' => $key)) . '<br />';
1541                 }
1542             }
1543             if (!$questionlist) { // no questions were selected
1544                 redirect($this->baseurl);
1545             }
1546             $questionlist = rtrim($questionlist, ',');
1548             // Add an explanation about questions in use
1549             if ($inuse) {
1550                 $questionnames .= '<br />'.get_string('questionsinuse', 'question');
1551             }
1552             $baseurl = new moodle_url('edit.php', $this->baseurl->params());
1553             $deleteurl = new moodle_url($baseurl, array('deleteselected'=>$questionlist, 'confirm'=>md5($questionlist), 'sesskey'=>sesskey()));
1555             echo $OUTPUT->confirm(get_string('deletequestionscheck', 'question', $questionnames), $deleteurl, $baseurl);
1557             return true;
1558         }
1559     }
1562 /**
1563  * Common setup for all pages for editing questions.
1564  * @param string $baseurl the name of the script calling this funciton. For examle 'qusetion/edit.php'.
1565  * @param string $edittab code for this edit tab
1566  * @param bool $requirecmid require cmid? default false
1567  * @param bool $requirecourseid require courseid, if cmid is not given? default true
1568  * @return array $thispageurl, $contexts, $cmid, $cm, $module, $pagevars
1569  */
1570 function question_edit_setup($edittab, $baseurl, $requirecmid = false, $requirecourseid = true) {
1571     global $DB, $PAGE;
1573     $thispageurl = new moodle_url($baseurl);
1574     $thispageurl->remove_all_params(); // We are going to explicity add back everything important - this avoids unwanted params from being retained.
1576     if ($requirecmid){
1577         $cmid =required_param('cmid', PARAM_INT);
1578     } else {
1579         $cmid = optional_param('cmid', 0, PARAM_INT);
1580     }
1581     if ($cmid){
1582         list($module, $cm) = get_module_from_cmid($cmid);
1583         $courseid = $cm->course;
1584         $thispageurl->params(compact('cmid'));
1585         require_login($courseid, false, $cm);
1586         $thiscontext = get_context_instance(CONTEXT_MODULE, $cmid);
1587     } else {
1588         $module = null;
1589         $cm = null;
1590         if ($requirecourseid){
1591             $courseid  = required_param('courseid', PARAM_INT);
1592         } else {
1593             $courseid  = optional_param('courseid', 0, PARAM_INT);
1594         }
1595         if ($courseid){
1596             $thispageurl->params(compact('courseid'));
1597             require_login($courseid, false);
1598             $thiscontext = get_context_instance(CONTEXT_COURSE, $courseid);
1599         } else {
1600             $thiscontext = null;
1601         }
1602     }
1604     if ($thiscontext){
1605         $contexts = new question_edit_contexts($thiscontext);
1606         $contexts->require_one_edit_tab_cap($edittab);
1608     } else {
1609         $contexts = null;
1610     }
1612     $PAGE->set_pagelayout('admin');
1614     $pagevars['qpage'] = optional_param('qpage', -1, PARAM_INT);
1616     //pass 'cat' from page to page and when 'category' comes from a drop down menu
1617     //then we also reset the qpage so we go to page 1 of
1618     //a new cat.
1619     $pagevars['cat'] = optional_param('cat', 0, PARAM_SEQUENCE); // if empty will be set up later
1620     if ($category = optional_param('category', 0, PARAM_SEQUENCE)) {
1621         if ($pagevars['cat'] != $category) { // is this a move to a new category?
1622             $pagevars['cat'] = $category;
1623             $pagevars['qpage'] = 0;
1624         }
1625     }
1626     if ($pagevars['cat']){
1627         $thispageurl->param('cat', $pagevars['cat']);
1628     }
1629     if (strpos($baseurl, '/question/') === 0) {
1630         navigation_node::override_active_url($thispageurl);
1631     }
1633     if ($pagevars['qpage'] > -1) {
1634         $thispageurl->param('qpage', $pagevars['qpage']);
1635     } else {
1636         $pagevars['qpage'] = 0;
1637     }
1639     $pagevars['qperpage'] = optional_param('qperpage', -1, PARAM_INT);
1640     if ($pagevars['qperpage'] > -1) {
1641         $thispageurl->param('qperpage', $pagevars['qperpage']);
1642     } else {
1643         $pagevars['qperpage'] = DEFAULT_QUESTIONS_PER_PAGE;
1644     }
1646     for ($i = 1; $i <= question_bank_view::MAX_SORTS; $i++) {
1647         $param = 'qbs' . $i;
1648         if (!$sort = optional_param($param, '', PARAM_ALPHAEXT)) {
1649             break;
1650         }
1651         $thispageurl->param($param, $sort);
1652     }
1654     $defaultcategory = question_make_default_categories($contexts->all());
1656     $contextlistarr = array();
1657     foreach ($contexts->having_one_edit_tab_cap($edittab) as $context){
1658         $contextlistarr[] = "'$context->id'";
1659     }
1660     $contextlist = join($contextlistarr, ' ,');
1661     if (!empty($pagevars['cat'])){
1662         $catparts = explode(',', $pagevars['cat']);
1663         if (!$catparts[0] || (false !== array_search($catparts[1], $contextlistarr)) ||
1664                 !$DB->count_records_select("question_categories", "id = ? AND contextid = ?", array($catparts[0], $catparts[1]))) {
1665             print_error('invalidcategory', 'question');
1666         }
1667     } else {
1668         $category = $defaultcategory;
1669         $pagevars['cat'] = "$category->id,$category->contextid";
1670     }
1672     if(($recurse = optional_param('recurse', -1, PARAM_BOOL)) != -1) {
1673         $pagevars['recurse'] = $recurse;
1674         $thispageurl->param('recurse', $recurse);
1675     } else {
1676         $pagevars['recurse'] = 1;
1677     }
1679     if(($showhidden = optional_param('showhidden', -1, PARAM_BOOL)) != -1) {
1680         $pagevars['showhidden'] = $showhidden;
1681         $thispageurl->param('showhidden', $showhidden);
1682     } else {
1683         $pagevars['showhidden'] = 0;
1684     }
1686     if(($showquestiontext = optional_param('qbshowtext', -1, PARAM_BOOL)) != -1) {
1687         $pagevars['qbshowtext'] = $showquestiontext;
1688         $thispageurl->param('qbshowtext', $showquestiontext);
1689     } else {
1690         $pagevars['qbshowtext'] = 0;
1691     }
1693     //category list page
1694     $pagevars['cpage'] = optional_param('cpage', 1, PARAM_INT);
1695     if ($pagevars['cpage'] != 1){
1696         $thispageurl->param('cpage', $pagevars['cpage']);
1697     }
1699     return array($thispageurl, $contexts, $cmid, $cm, $module, $pagevars);
1702 /**
1703  * Make sure user is logged in as required in this context.
1704  */
1705 function require_login_in_context($contextorid = null){
1706     global $DB, $CFG;
1707     if (!is_object($contextorid)){
1708         $context = get_context_instance_by_id($contextorid);
1709     } else {
1710         $context = $contextorid;
1711     }
1712     if ($context && ($context->contextlevel == CONTEXT_COURSE)) {
1713         require_login($context->instanceid);
1714     } else if ($context && ($context->contextlevel == CONTEXT_MODULE)) {
1715         if ($cm = $DB->get_record('course_modules',array('id' =>$context->instanceid))) {
1716             if (!$course = $DB->get_record('course', array('id' => $cm->course))) {
1717                 print_error('invalidcourseid');
1718             }
1719             require_course_login($course, true, $cm);
1721         } else {
1722             print_error('invalidcoursemodule');
1723         }
1724     } else if ($context && ($context->contextlevel == CONTEXT_SYSTEM)) {
1725         if (!empty($CFG->forcelogin)) {
1726             require_login();
1727         }
1729     } else {
1730         require_login();
1731     }
1734 /**
1735  * Print a form to let the user choose which question type to add.
1736  * When the form is submitted, it goes to the question.php script.
1737  * @param $hiddenparams hidden parameters to add to the form, in addition to
1738  * the qtype radio buttons.
1739  */
1740 function print_choose_qtype_to_add_form($hiddenparams) {
1741     global $CFG, $PAGE, $OUTPUT;
1742     $PAGE->requires->js('/question/qbank.js');
1743     echo '<div id="chooseqtypehead" class="hd">' . "\n";
1744     echo $OUTPUT->heading(get_string('chooseqtypetoadd', 'question'), 3);
1745     echo "</div>\n";
1746     echo '<div id="chooseqtype">' . "\n";
1747     echo '<form action="' . $CFG->wwwroot . '/question/question.php" method="get"><div id="qtypeformdiv">' . "\n";
1748     foreach ($hiddenparams as $name => $value) {
1749         echo '<input type="hidden" name="' . s($name) . '" value="' . s($value) . '" />' . "\n";
1750     }
1751     echo "</div>\n";
1752     echo '<div class="qtypes">' . "\n";
1753     echo '<div class="instruction">' . get_string('selectaqtypefordescription', 'question') . "</div>\n";
1754     echo '<div class="realqtypes">' . "\n";
1755     $fakeqtypes = array();
1756     foreach (question_bank::get_creatable_qtypes() as $qtype) {
1757         if ($qtype->is_real_question_type()) {
1758             print_qtype_to_add_option($qtype);
1759         } else {
1760             $fakeqtypes[] = $qtype;
1761         }
1762     }
1763     echo "</div>\n";
1764     echo '<div class="fakeqtypes">' . "\n";
1765     foreach ($fakeqtypes as $qtype) {
1766         print_qtype_to_add_option($qtype);
1767     }
1768     echo "</div>\n";
1769     echo "</div>\n";
1770     echo '<div class="submitbuttons">' . "\n";
1771     echo '<input type="submit" value="' . get_string('next') . '" id="chooseqtype_submit" />' . "\n";
1772     echo '<input type="submit" id="chooseqtypecancel" name="addcancel" value="' . get_string('cancel') . '" />' . "\n";
1773     echo "</div></form>\n";
1774     echo "</div>\n";
1775     $PAGE->requires->js_init_call('qtype_chooser.init', array('chooseqtype'));
1778 /**
1779  * Private function used by the preceding one.
1780  * @param question_type $qtype the question type.
1781  */
1782 function print_qtype_to_add_option($qtype) {
1783     echo '<div class="qtypeoption">' . "\n";
1784     echo '<label for="' . $qtype->plugin_name() . '">';
1785     echo '<input type="radio" name="qtype" id="' . $qtype->plugin_name() .
1786             '" value="' . $qtype->name() . '" />';
1787     echo '<span class="qtypename">';
1788     $fakequestion = new stdClass();
1789     $fakequestion->qtype = $qtype->name();
1790     echo print_question_icon($fakequestion);
1791     echo $qtype->menu_name() . '</span><span class="qtypesummary">' .
1792             get_string('pluginnamesummary', $qtype->plugin_name());
1793     echo "</span></label>\n";
1794     echo "</div>\n";
1797 /**
1798  * Print a button for creating a new question. This will open question/addquestion.php,
1799  * which in turn goes to question/question.php before getting back to $params['returnurl']
1800  * (by default the question bank screen).
1801  *
1802  * @param int $categoryid The id of the category that the new question should be added to.
1803  * @param array $params Other paramters to add to the URL. You need either $params['cmid'] or
1804  *      $params['courseid'], and you should probably set $params['returnurl']
1805  * @param string $caption the text to display on the button.
1806  * @param string $tooltip a tooltip to add to the button (optional).
1807  * @param bool $disabled if true, the button will be disabled.
1808  */
1809 function create_new_question_button($categoryid, $params, $caption, $tooltip = '', $disabled = false) {
1810     global $CFG, $PAGE, $OUTPUT;
1811     static $choiceformprinted = false;
1812     $params['category'] = $categoryid;
1813     $url = new moodle_url('/question/addquestion.php', $params);
1814     echo $OUTPUT->single_button($url, $caption, 'get', array('disabled'=>$disabled, 'title'=>$tooltip));
1816     $PAGE->requires->yui2_lib('dragdrop');
1817     $PAGE->requires->yui2_lib('container');
1818     if (!$choiceformprinted) {
1819         echo '<div id="qtypechoicecontainer">';
1820         print_choose_qtype_to_add_form(array());
1821         echo "</div>\n";
1822         $choiceformprinted = true;
1823     }