web service MDL-12886 implement authentication token systemprototype
[moodle.git] / question / editlib.php
CommitLineData
516cf3eb 1<?php // $Id$
f4b879dd 2
3///////////////////////////////////////////////////////////////////////////
4// //
5// NOTICE OF COPYRIGHT //
6// //
7// Moodle - Modular Object-Oriented Dynamic Learning Environment //
8// http://moodle.org //
9// //
10// Copyright (C) 1999 onwards Martin Dougiamas and others //
11// //
12// This program is free software; you can redistribute it and/or modify //
13// it under the terms of the GNU General Public License as published by //
14// the Free Software Foundation; either version 2 of the License, or //
15// (at your option) any later version. //
16// //
17// This program is distributed in the hope that it will be useful, //
18// but WITHOUT ANY WARRANTY; without even the implied warranty of //
19// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //
20// GNU General Public License for more details: //
21// //
22// http://www.gnu.org/copyleft/gpl.html //
23// //
24///////////////////////////////////////////////////////////////////////////
25
516cf3eb 26/**
b72ff476 27 * Functions used to show question editing interface
4323d029 28 *
4323d029 29 * @license http://www.gnu.org/copyleft/gpl.html GNU Public License
30 * @package questionbank
f4b879dd 31 *//** */
516cf3eb 32
4fbfd971 33require_once($CFG->libdir.'/questionlib.php');
516cf3eb 34
f92cf442 35define('DEFAULT_QUESTIONS_PER_PAGE', 20);
36
f4b879dd 37function get_module_from_cmid($cmid) {
f34488b2 38 global $CFG, $DB;
39 if (!$cmrec = $DB->get_record_sql("SELECT cm.*, md.name as modname
40 FROM {course_modules} cm,
41 {modules} md
42 WHERE cm.id = ? AND
43 md.id = cm.module", array($cmid))){
1eda5201 44 print_error('invalidcoursemodule');
f34488b2 45 } elseif (!$modrec =$DB->get_record($cmrec->modname, array('id' => $cmrec->instance))) {
1eda5201 46 print_error('invalidcoursemodule');
86909ce0 47 }
48 $modrec->instance = $modrec->id;
d0e88092 49 $modrec->cmid = $cmrec->id;
ea16c547 50 $cmrec->name = $modrec->name;
271e6dec 51
86909ce0 52 return array($modrec, $cmrec);
53}
4fbfd971 54/**
55* Function to read all questions for category into big array
56*
57* @param int $category category number
36e2232e 58* @param bool $noparent if true only questions with NO parent will be selected
59* @param bool $recurse include subdirectories
5fd8f999 60* @param bool $export set true if this is called by questionbank export
4fbfd971 61* @author added by Howard Miller June 2004
62*/
5fd8f999 63function get_questions_category( $category, $noparent=false, $recurse=true, $export=true ) {
4fbfd971 64
f34488b2 65 global $QTYPES, $DB;
4fbfd971 66
67 // questions will be added to an array
68 $qresults = array();
69
70 // build sql bit for $noparent
71 $npsql = '';
72 if ($noparent) {
73 $npsql = " and parent='0' ";
74 }
75
36e2232e 76 // get (list) of categories
77 if ($recurse) {
78 $categorylist = question_categorylist( $category->id );
79 }
80 else {
81 $categorylist = $category->id;
82 }
83
4fbfd971 84 // get the list of questions for the category
f34488b2 85 list ($usql, $params) = $DB->get_in_or_equal(explode(',', $categorylist));
86 if ($questions = $DB->get_records_select("question","category $usql $npsql", $params, "qtype, name ASC")) {
4fbfd971 87
88 // iterate through questions, getting stuff we need
89 foreach($questions as $question) {
90 $questiontype = $QTYPES[$question->qtype];
5fd8f999 91 $question->export_process = $export;
4fbfd971 92 $questiontype->get_question_options( $question );
93 $qresults[] = $question;
94 }
95 }
96
97 return $qresults;
98}
99
df4e2244 100/**
101 * @param integer $categoryid a category id.
102 * @return boolean whether this is the only top-level category in a context.
103 */
104function question_is_only_toplevel_category_in_context($categoryid) {
105 global $DB;
106 return 1 == $DB->count_records_sql("
107 SELECT count(*)
108 FROM {question_categories} c1,
109 {question_categories} c2
110 WHERE c2.id = ?
111 AND c1.contextid = c2.contextid
112 AND c1.parent = 0 AND c2.parent = 0", array($categoryid));
113}
4fbfd971 114
df4e2244 115/**
116 * Check whether this user is allowed to delete this category.
117 *
118 * @param integer $todelete a category id.
119 */
120function question_can_delete_cat($todelete) {
121 global $DB;
122 if (question_is_only_toplevel_category_in_context($todelete)) {
ac93d63d 123 print_error('cannotdeletecate', 'question');
271e6dec 124 } else {
df4e2244 125 $contextid = $DB->get_field('question_categories', 'contextid', array('id' => $todelete));
271e6dec 126 require_capability('moodle/question:managecategory', get_context_instance_by_id($contextid));
127 }
128}
f4b879dd 129
46795afc 130abstract class question_bank_column_base {
e4d1d5e0 131 /**
132 * @var question_bank_view
133 */
5bd22790 134 protected $qbank;
135
136 /**
137 * Constructor.
138 * @param $qbank the question_bank_view we are helping to render.
139 */
140 public function __construct(question_bank_view $qbank) {
141 $this->qbank = $qbank;
142 $this->init();
143 }
144
145 /**
146 * A chance for subclasses to initialise themselves, for example to load lang strings,
147 * without having to override the constructor.
148 */
149 protected function init() {
150 }
46795afc 151
152 /**
153 * Output the column header cell.
154 * @param integer $currentsort 0 for none. 1 for normal sort, -1 for reverse sort.
155 */
5bd22790 156 public function display_header() {
e4d1d5e0 157 echo '<th class="header ' . $this->get_name() . '" scope="col">';
5bd22790 158 $sortable = $this->is_sortable();
159 $name = $this->get_name();
160 $title = $this->get_title();
e4d1d5e0 161 $tip = $this->get_title_tip();
5bd22790 162 if (is_array($sortable)) {
163 if ($title) {
164 echo '<div class="title">' . $title . '</div>';
165 }
166 $links = array();
167 foreach ($sortable as $subsort => $details) {
e4d1d5e0 168 $links[] = $this->make_sort_link($name . '_' . $subsort,
169 $details['title'], '', !empty($details['reverse']));
5bd22790 170 }
171 echo implode(' / ', $links);
172 } else if ($sortable) {
e4d1d5e0 173 echo $this->make_sort_link($name, $title, $tip);
5bd22790 174 } else {
0ff5afdf 175 if ($tip) {
176 echo '<span title="' . $tip . '">';
177 }
5bd22790 178 echo $title;
0ff5afdf 179 if ($tip) {
180 echo '</span>';
181 }
5bd22790 182 }
183 echo "</th>\n";
184 }
185
186 /**
187 * Title for this column. Not used if is_sortable returns an array.
188 * @param object $question the row from the $question table, augmented with extra information.
189 * @param string $rowclasses CSS class names that should be applied to this row of output.
190 */
971c6fca 191 abstract protected function get_title();
0ff5afdf 192
193 /**
194 * @return string a fuller version of the name. Use this when get_title() returns
195 * something very short, and you want a longer version as a tool tip.
196 */
197 protected function get_title_tip() {
5bd22790 198 return '';
199 }
200
201 /**
202 * Get a link that changes the sort order, and indicates the current sort state.
203 * @param $name internal name used for this type of sorting.
204 * @param $currentsort the current sort order -1, 0, 1 for descending, none, ascending.
205 * @param $title the link text.
206 * @param $defaultreverse whether the default sort order for this column is descending, rather than ascending.
207 * @return string HTML fragment.
208 */
e4d1d5e0 209 protected function make_sort_link($sort, $title, $tip, $defaultreverse = false) {
210 $currentsort = $this->qbank->get_primary_sort_order($sort);
5bd22790 211 $newsortreverse = $defaultreverse;
212 if ($currentsort) {
213 $newsortreverse = $currentsort > 0;
214 }
0ff5afdf 215 if (!$tip) {
216 $tip = $title;
217 }
5bd22790 218 if ($newsortreverse) {
0ff5afdf 219 $tip = get_string('sortbyxreverse', '', $tip);
5bd22790 220 } else {
0ff5afdf 221 $tip = get_string('sortbyx', '', $tip);
5bd22790 222 }
e4d1d5e0 223 $link = '<a href="' . $this->qbank->new_sort_url($sort, $newsortreverse) . '" title="' . $tip . '">';
224 $link .= $title;
5bd22790 225 if ($currentsort) {
e4d1d5e0 226 $link .= $this->get_sort_icon($currentsort < 0);
5bd22790 227 }
e4d1d5e0 228 $link .= '</a>';
229 return $link;
5bd22790 230 }
231
232 /**
233 * Get an icon representing the corrent sort state.
234 * @param $reverse sort is descending, not ascending.
235 * @return string HTML image tag.
236 */
237 protected function get_sort_icon($reverse) {
238 global $CFG;
239 if ($reverse) {
240 return ' <img src="' . $CFG->pixpath . '/t/up.gif" alt="' . get_string('desc') . '" />';
241 } else {
242 return ' <img src="' . $CFG->pixpath . '/t/down.gif" alt="' . get_string('asc') . '" />';
243 }
46795afc 244 }
245
246 /**
247 * Output this column.
248 * @param object $question the row from the $question table, augmented with extra information.
249 * @param string $rowclasses CSS class names that should be applied to this row of output.
250 */
251 public function display($question, $rowclasses) {
252 $this->display_start($question, $rowclasses);
253 $this->display_content($question, $rowclasses);
254 $this->display_end($question, $rowclasses);
255 }
256
257 protected function display_start($question, $rowclasses) {
5bd22790 258 echo '<td class="' . $this->get_name() . '">';
46795afc 259 }
260
261 /**
262 * @param object $question the row from the $question table, augmented with extra information.
b221dc6f 263 * @return string internal name for this column. Used as a CSS class name,
264 * and to store information about the current sort. Must match PARAM_ALPHA.
46795afc 265 */
babdcb40 266 abstract public function get_name();
46795afc 267
268 /**
269 * Output the contents of this column.
270 * @param object $question the row from the $question table, augmented with extra information.
271 * @param string $rowclasses CSS class names that should be applied to this row of output.
272 */
273 abstract protected function display_content($question, $rowclasses);
274
275 protected function display_end($question, $rowclasses) {
5bd22790 276 echo "</td>\n";
46795afc 277 }
278
279 /**
280 * Return an array 'table_alias' => 'JOIN clause' to bring in any data that
281 * this column required.
282 *
283 * The return values for all the columns will be checked. It is OK if two
284 * columns join in the same table with the same alias and identical JOIN clauses.
285 * If to columns try to use the same alias with different joins, you get an error.
286 * The only table included by default is the question table, which is aliased to 'q'.
287 *
b221dc6f 288 * It is importnat that your join simply adds additional data (or NULLs) to the
289 * existing rows of the query. It must not cause additional rows.
290 *
46795afc 291 * @return array 'table_alias' => 'JOIN clause'
292 */
293 public function get_extra_joins() {
294 return array();
295 }
296
297 /**
298 * @return array fields required. use table alias 'q' for the question table, or one of the
299 * ones from get_extra_joins. Every field requested must specify a table prefix.
300 */
301 public function get_required_fields() {
302 return array();
303 }
304
305 /**
306 * Can this column be sorted on? You can return either:
307 * + false for no (the default),
5bd22790 308 * + a field name, if sorting this column corresponds to sorting on that datbase field.
309 * + an array of subnames to sort on as follows
310 * return array(
311 * 'firstname' => array('field' => 'uc.firstname', 'title' => get_string('firstname')),
312 * 'lastname' => array('field' => 'uc.lastname', 'field' => get_string('lastname')),
313 * );
314 * As well as field, and field, you can also add 'revers' => 1 if you want the default sort
315 * order to be DESC.
316 * @return mixed as above.
46795afc 317 */
318 public function is_sortable() {
319 return false;
320 }
321
322 /**
323 * Helper method for building sort clauses.
324 * @param boolean $reverse whether the normal direction should be reversed.
325 * @param string $normaldir 'ASC' or 'DESC'
326 * @return string 'ASC' or 'DESC'
327 */
5bd22790 328 protected function sortorder($reverse) {
329 if ($reverse) {
330 return ' DESC';
331 } else {
332 return ' ASC';
46795afc 333 }
334 }
335
336 /**
337 * @param $reverse Whether to sort in the reverse of the default sort order.
338 * @param $subsort if is_sortable returns an array of subnames, then this will be
339 * one of those. Otherwise will be empty.
340 * @return string some SQL to go in the order by clause.
341 */
342 public function sort_expression($reverse, $subsort) {
5bd22790 343 $sortable = $this->is_sortable();
344 if (is_array($sortable)) {
345 if (array_key_exists($subsort, $sortable)) {
e4d1d5e0 346 return $sortable[$subsort]['field'] . $this->sortorder($reverse, !empty($sortable[$subsort]['reverse']));
5bd22790 347 } else {
348 throw new coding_exception('Unexpected $subsort type: ' . $subsort);
349 }
350 } else if ($sortable) {
351 return $sortable . $this->sortorder($reverse);
352 } else {
353 throw new coding_exception('sort_expression called on a non-sortable column.');
354 }
46795afc 355 }
356}
357
358/**
359 * A column with a checkbox for each question with name q{questionid}.
360 */
361class question_bank_checkbox_column extends question_bank_column_base {
362 protected $strselect;
363
5bd22790 364 public function init() {
46795afc 365 $this->strselect = get_string('select', 'quiz');
366 }
367
babdcb40 368 public function get_name() {
46795afc 369 return 'checkbox';
370 }
371
5bd22790 372 protected function get_title() {
373 return '<input type="checkbox" disabled="disabled" />';
374 }
375
0ff5afdf 376 protected function get_title_tip() {
377 return get_string('selectquestionsforbulk', 'question');
378 }
379
46795afc 380 protected function display_content($question, $rowclasses) {
381 echo '<input title="' . $this->strselect . '" type="checkbox" name="q' .
382 $question->id . '" id="checkq' . $question->id . '" value="1" />';
383 }
384
385 public function get_required_fields() {
386 return array('q.id');
387 }
388}
389
390/**
391 * A column type for the name of the question type.
392 */
393class question_bank_question_type_column extends question_bank_column_base {
babdcb40 394 public function get_name() {
46795afc 395 return 'qtype';
396 }
397
5bd22790 398 protected function get_title() {
399 return get_string('qtypeveryshort', 'question');
400 }
401
0ff5afdf 402 protected function get_title_tip() {
403 return get_string('questiontype', 'question');
404 }
405
46795afc 406 protected function display_content($question, $rowclasses) {
407 echo print_question_icon($question);
408 }
409
410 public function get_required_fields() {
411 return array('q.qtype');
412 }
413
414 public function is_sortable() {
5bd22790 415 return 'q.qtype';
46795afc 416 }
417}
418
419/**
420 * A column type for the name of the question name.
421 */
422class question_bank_question_name_column extends question_bank_column_base {
971c6fca 423 protected $checkboxespresent = null;
424
babdcb40 425 public function get_name() {
46795afc 426 return 'questionname';
427 }
428
5bd22790 429 protected function get_title() {
430 return get_string('question');
431 }
432
971c6fca 433 protected function label_for($question) {
434 if (is_null($this->checkboxespresent)) {
435 $this->checkboxespresent = $this->qbank->has_column('checkbox');
436 }
437 if ($this->checkboxespresent) {
438 return 'checkq' . $question->id;
439 } else {
440 return '';
441 }
442 }
443
46795afc 444 protected function display_content($question, $rowclasses) {
971c6fca 445 $labelfor = $this->label_for($question);
446 if ($labelfor) {
447 echo '<label for="' . $labelfor . '">';
448 }
46795afc 449 echo format_string($question->name);
971c6fca 450 if ($labelfor) {
451 echo '</label>';
452 }
46795afc 453 }
454
455 public function get_required_fields() {
971c6fca 456 return array('q.id', 'q.name');
46795afc 457 }
458
459 public function is_sortable() {
5bd22790 460 return 'q.name';
46795afc 461 }
462}
463
464/**
465 * A column type for the name of the question creator.
466 */
467class question_bank_creator_name_column extends question_bank_column_base {
babdcb40 468 public function get_name() {
46795afc 469 return 'creatorname';
470 }
471
5bd22790 472 protected function get_title() {
473 return get_string('createdby', 'question');
474 }
475
46795afc 476 protected function display_content($question, $rowclasses) {
477 if (!empty($question->creatorfirstname) && !empty($question->creatorlastname)) {
478 $u = new stdClass;
479 $u->firstname = $question->creatorfirstname;
480 $u->lastname = $question->creatorlastname;
481 echo fullname($u);
482 }
483 }
484
485 public function get_extra_joins() {
486 return array('uc' => 'LEFT JOIN {user} uc ON uc.id = q.createdby');
487 }
488
489 public function get_required_fields() {
490 return array('uc.firstname AS creatorfirstname', 'uc.lastname AS creatorlastname');
491 }
492
493 public function is_sortable() {
5bd22790 494 return array(
495 'firstname' => array('field' => 'uc.firstname', 'title' => get_string('firstname')),
496 'lastname' => array('field' => 'uc.lastname', 'title' => get_string('lastname')),
497 );
46795afc 498 }
499}
500
501/**
502 * A column type for the name of the question last modifier.
503 */
504class question_bank_modifier_name_column extends question_bank_column_base {
babdcb40 505 public function get_name() {
46795afc 506 return 'modifiername';
507 }
508
5bd22790 509 protected function get_title() {
510 return get_string('lastmodifiedby', 'question');
511 }
512
46795afc 513 protected function display_content($question, $rowclasses) {
514 if (!empty($question->modifierfirstname) && !empty($question->modifierlastname)) {
515 $u = new stdClass;
516 $u->firstname = $question->modifierfirstname;
517 $u->lastname = $question->modifierlastname;
518 echo fullname($u);
519 }
520 }
521
522 public function get_extra_joins() {
523 return array('um' => 'LEFT JOIN {user} um ON um.id = q.modifiedby');
524 }
525
526 public function get_required_fields() {
527 return array('um.firstname AS modifierfirstname', 'um.lastname AS modifierlastname');
528 }
529
530 public function is_sortable() {
5bd22790 531 return array(
532 'firstname' => array('field' => 'um.firstname', 'title' => get_string('firstname')),
533 'lastname' => array('field' => 'um.lastname', 'title' => get_string('lastname')),
534 );
46795afc 535 }
536}
537
538/**
539 * A base class for actions that are an icon that lets you manipulate the question in some way.
540 */
541abstract class question_bank_action_column_base extends question_bank_column_base {
5bd22790 542
543 protected function get_title() {
544 return '&#160;';
545 }
546
46795afc 547 protected function print_icon($icon, $title, $url) {
548 global $CFG;
549 echo '<a title="' . $title . '" href="' . $url . '">
550 <img src="' . $CFG->pixpath . '/t/' . $icon . '" class="iconsmall" alt="' . $title . '" /></a>';
551 }
552
553 public function get_required_fields() {
554 return array('q.id');
555 }
556}
557
558class question_bank_edit_action_column extends question_bank_action_column_base {
559 protected $stredit;
560 protected $strview;
46795afc 561
5bd22790 562 public function init() {
563 parent::init();
46795afc 564 $this->stredit = get_string('edit');
565 $this->strview = get_string('view');
566 }
567
babdcb40 568 public function get_name() {
46795afc 569 return 'editaction';
570 }
571
572 protected function display_content($question, $rowclasses) {
573 if (question_has_capability_on($question, 'edit') ||
574 question_has_capability_on($question, 'move')) {
5bd22790 575 $this->print_icon('edit', $this->stredit, $this->qbank->edit_question_url($question->id));
46795afc 576 } else {
5bd22790 577 $this->print_icon('info', $this->strview, $this->qbank->edit_question_url($question->id));
46795afc 578 }
579 }
580}
581
582class question_bank_preview_action_column extends question_bank_action_column_base {
583 protected $strpreview;
46795afc 584
5bd22790 585 public function init() {
586 parent::init();
e4d1d5e0 587 $this->strpreview = get_string('preview');
46795afc 588 }
589
babdcb40 590 public function get_name() {
46795afc 591 return 'previewaction';
592 }
593
594 protected function display_content($question, $rowclasses) {
e4d1d5e0 595 global $CFG;
46795afc 596 if (question_has_capability_on($question, 'use')) {
5bd22790 597 link_to_popup_window($this->qbank->preview_question_url($question->id), 'questionpreview',
46795afc 598 ' <img src="' . $CFG->pixpath . '/t/preview.gif" class="iconsmall" alt="' . $this->strpreview . '" />',
599 0, 0, $this->strpreview, QUESTION_PREVIEW_POPUP_OPTIONS);
600 }
601 }
602
603 public function get_required_fields() {
604 return array('q.id');
605 }
606}
607
608class question_bank_move_action_column extends question_bank_action_column_base {
609 protected $strmove;
46795afc 610
5bd22790 611 public function init() {
612 parent::init();
46795afc 613 $this->strmove = get_string('move');
614 }
615
babdcb40 616 public function get_name() {
617 return 'moveaction';
46795afc 618 }
619
620 protected function display_content($question, $rowclasses) {
621 if (question_has_capability_on($question, 'move')) {
e4d1d5e0 622 $this->print_icon('move', $this->strmove, $this->qbank->move_question_url($question->id));
46795afc 623 }
624 }
625}
626
627/**
628 * action to delete (or hide) a question, or restore a previously hidden question.
629 */
630class question_bank_delete_action_column extends question_bank_action_column_base {
631 protected $strdelete;
632 protected $strrestore;
46795afc 633
5bd22790 634 public function init() {
635 parent::init();
46795afc 636 $this->strdelete = get_string('delete');
637 $this->strrestore = get_string('restore');
638 }
639
babdcb40 640 public function get_name() {
46795afc 641 return 'deleteaction';
642 }
643
644 protected function display_content($question, $rowclasses) {
645 if (question_has_capability_on($question, 'edit')) {
646 if ($question->hidden) {
5bd22790 647 $this->print_icon('restore', $this->strrestore, $this->qbank->base_url()->out(false, array('unhide' => $question->id)));
46795afc 648 } else {
e4d1d5e0 649 $this->print_icon('delete', $this->strdelete,
5bd22790 650 $this->qbank->base_url()->out(false, array('deleteselected' => $question->id, 'q' . $question->id => 1)));
46795afc 651 }
652 }
653 }
654
655 public function get_required_fields() {
656 return array('q.id', 'q.hidden');
657 }
658}
659
e4d1d5e0 660/**
661 * Base class for 'columns' that are actually displayed as a row following the main question row.
662 */
663abstract class question_bank_row_base extends question_bank_column_base {
664 // TODO
665}
666
667/**
668 * A column type for the name of the question name.
669 */
670class question_bank_question_text_row extends question_bank_row_base {
671 public function get_name() {
672 return 'questiontext';
673 }
674
675 protected function get_title() {
676 return get_string('questiontext', 'question');
677 }
678
679 protected function display_content($question, $rowclasses) {
680 // TODO
681// echo '<tr><td colspan="3" ' . $textclass . '>';
682// $formatoptions = new stdClass;
683// $formatoptions->noclean = true;
684// $formatoptions->para = false;
685// echo format_text($question->questiontext, $question->questiontextformat,
686// $formatoptions, $this->course->id);
687// echo "</td></tr>\n";
688 }
689
690 public function get_required_fields() {
691 return array('q.questiontext');
692 }
693}
694
4fbfd971 695/**
f4b879dd 696 * This class prints a view of the question bank, including
697 * + Some controls to allow users to to select what is displayed.
698 * + A list of questions as a table.
699 * + Further controls to do things with the questions.
700 *
701 * This class gives a basic view, and provides plenty of hooks where subclasses
702 * can override parts of the display.
703 *
704 * The list of questions presented as a table is generated by creating a list of
705 * question_bank_column objects, one for each 'column' to be displayed. These
706 * manage
707 * + outputting the contents of that column, given a $question object, but also
708 * + generating the right fragments of SQL to ensure the necessary data is present,
709 * and sorted in the right order.
710 * + outputting table headers.
4fbfd971 711 */
f4b879dd 712class question_bank_view {
e4d1d5e0 713 const MAX_SORTS = 3;
714
5bd22790 715 protected $baseurl;
716 protected $editquestionurl;
717 protected $quizorcourseid;
718 protected $contexts;
719 protected $cm;
971c6fca 720 protected $course;
b221dc6f 721 protected $knowncolumntypes;
722 protected $visiblecolumns;
723 protected $requiredcolumns;
724 protected $sort;
725 protected $countsql;
726 protected $loadsql;
e4d1d5e0 727 protected $sqlparams;
5bd22790 728
971c6fca 729 public function __construct($contexts, $pageurl, $course, $cm = null) {
730 global $CFG;
516cf3eb 731
5bd22790 732 $this->contexts = $contexts;
733 $this->baseurl = $pageurl;
971c6fca 734 $this->course = $course;
5bd22790 735 $this->cm = $cm;
736
737 if (!empty($cm) && $cm->modname == 'quiz') {
738 $this->quizorcourseid = '&amp;quizid=' . $cm->instance;
739 } else {
971c6fca 740 $this->quizorcourseid = '&amp;courseid=' .$this->course->id;
5bd22790 741 }
742
743 // Create the url of the new question page to forward to.
744 $this->editquestionurl = new moodle_url("$CFG->wwwroot/question/question.php",
745 array('returnurl' => $pageurl->out()));
746 if ($cm !== null){
747 $this->editquestionurl->param('cmid', $cm->id);
748 } else {
971c6fca 749 $this->editquestionurl->param('courseid', $this->course->id);
5bd22790 750 }
b221dc6f 751
752 $this->init_column_types();
971c6fca 753 $this->init_columns($this->wanted_columns());
b221dc6f 754 $this->init_sort();
755 }
756
971c6fca 757 protected function wanted_columns() {
758 return array('checkbox', 'qtype', 'questionname', 'creatorname',
759 'modifiername', 'editaction', 'previewaction', 'moveaction', 'deleteaction');
760 }
761
762 protected function know_field_types() {
763 return array(
b221dc6f 764 new question_bank_checkbox_column($this),
765 new question_bank_question_type_column($this),
766 new question_bank_question_name_column($this),
767 new question_bank_creator_name_column($this),
768 new question_bank_modifier_name_column($this),
769 new question_bank_edit_action_column($this),
770 new question_bank_preview_action_column($this),
771 new question_bank_move_action_column($this),
772 new question_bank_delete_action_column($this),
773 );
971c6fca 774 }
775
776 protected function init_column_types() {
b221dc6f 777 $this->knowncolumntypes = array();
971c6fca 778 foreach ($this->know_field_types() as $col) {
b221dc6f 779 $this->knowncolumntypes[$col->get_name()] = $col;
780 }
781 }
782
783 protected function init_columns($wanted) {
784 $this->visiblecolumns = array();
785 foreach ($wanted as $colname) {
786 if (!isset($this->knowncolumntypes[$colname])) {
787 throw new coding_exception('Unknown column type ' . $colname . ' requested in init columns.');
788 }
789 $this->visiblecolumns[$colname] = $this->knowncolumntypes[$colname];
790 }
791 $this->requiredcolumns = $this->visiblecolumns;
792 }
793
e4d1d5e0 794 /**
795 * @param string $colname a column internal name.
796 * @return boolean is this column included in the output?
797 */
798 public function has_column($colname) {
799 return isset($this->visiblecolumns[$colname]);
800 }
801
b221dc6f 802 protected function init_sort() {
803 $this->init_sort_from_params();
804 if (empty($this->sort)) {
805 $this->sort = $this->default_sort();
806 }
807 }
808
809 /**
810 * Deal with a sort name of the forum columnname, or colname_subsort by
811 * breaking it up, validating the bits that are presend, and returning them.
812 * If there is no subsort, then $subsort is returned as ''.
813 * @return array array($colname, $subsort).
814 */
815 protected function parse_subsort($sort) {
816 /// Do the parsing.
817 if (strpos($sort, '_') !== false) {
818 list($colname, $subsort) = explode('_', $sort, 2);
819 } else {
820 $colname = $sort;
821 $subsort = '';
822 }
823 /// Validate the column name.
824 if (!isset($this->knowncolumntypes[$colname]) || !$this->knowncolumntypes[$colname]->is_sortable()) {
e4d1d5e0 825 for ($i = 1; $i <= question_bank_view::MAX_SORTS; $i++) {
826 $this->baseurl->remove_params('qbs' . $i);
827 }
b221dc6f 828 throw new moodle_exception('unknownsortcolumn', '', $link = $this->baseurl->out(), $colname);
829 }
830 /// Validate the subsort, if present.
831 if ($subsort) {
832 $subsorts = $this->knowncolumntypes[$colname]->is_sortable();
833 if (!is_array($subsorts) || !isset($subsorts[$subsort])) {
834 throw new moodle_exception('unknownsortcolumn', '', $link = $this->baseurl->out(), $sort);
835 }
836 }
837 return array($colname, $subsort);
838 }
839
840 protected function init_sort_from_params() {
841 $this->sort = array();
e4d1d5e0 842 for ($i = 1; $i <= question_bank_view::MAX_SORTS; $i++) {
843 if (!$sort = optional_param('qbs' . $i, '', PARAM_ALPHAEXT)) {
b221dc6f 844 break;
845 }
846 // Work out the appropriate order.
847 $order = 1;
848 if ($sort[0] == '-') {
849 $order = -1;
e4d1d5e0 850 $sort = substr($sort, 1);
b221dc6f 851 if (!$sort) {
852 break;
853 }
854 }
855 // Deal with subsorts.
856 list($colname, $subsort) = $this->parse_subsort($sort);
857 $this->requiredcolumns[$colname] = $this->knowncolumntypes[$colname];
e4d1d5e0 858 $this->sort[$sort] = $order;
b221dc6f 859 }
860 }
861
e4d1d5e0 862 protected function sort_to_params($sorts) {
863 $params = array();
864 $i = 0;
865 foreach ($sorts as $sort => $order) {
866 $i += 1;
867 if ($order < 0) {
868 $sort = '-' . $sort;
869 }
870 $params['qbs' . $i] = $sort;
871 }
872 return $params;
873 }
874
b221dc6f 875 protected function default_sort() {
876 return array('qtype' => 1, 'questionname' => 1);
877 }
878
e4d1d5e0 879 /**
880 * @param $sort a column or column_subsort name.
881 * @return integer the current sort order for this column -1, 0, 1
882 */
883 public function get_primary_sort_order($sort) {
884 $order = reset($this->sort);
885 $primarysort = key($this->sort);
886 if ($sort == $primarysort) {
887 return $order;
888 } else {
889 return 0;
890 }
891 }
892
893 /**
894 * Get a URL to redisplay the page with a new sort for the question bank.
895 * @param string $sort the column, or column_subsort to sort on.
896 * @param boolean $newsortreverse whether to sort in reverse order.
897 * @return string The new URL.
898 */
899 public function new_sort_url($sort, $newsortreverse) {
900 if ($newsortreverse) {
901 $order = -1;
902 } else {
903 $order = 1;
904 }
905 // Tricky code to add the new sort at the start, removing it from where it was before, if it was present.
906 $newsort = array_reverse($this->sort);
907 if (isset($newsort[$sort])) {
908 unset($newsort[$sort]);
909 }
910 $newsort[$sort] = $order;
911 $newsort = array_reverse($newsort);
912 if (count($newsort) > question_bank_view::MAX_SORTS) {
913 $newsort = array_slice($newsort, 0, question_bank_view::MAX_SORTS, true);
914 }
915 return $this->baseurl->out(false, $this->sort_to_params($newsort));
916 }
917
918 protected function build_query_sql($category, $recurse, $showhidden) {
919 global $DB;
920
b221dc6f 921 /// Get the required tables.
922 $joins = array();
923 foreach ($this->requiredcolumns as $column) {
924 $extrajoins = $column->get_extra_joins();
925 foreach ($extrajoins as $prefix => $join) {
926 if (isset($joins[$prefix]) && $joins[$prefix] != $join) {
927 throw new coding_exception('Join ' . $join . ' conflicts with previous join ' . $joins[$prefix]);
928 }
929 $joins[$prefix] = $join;
930 }
931 }
932
933 /// Get the required fields.
e4d1d5e0 934 $fields = array('q.hidden', 'q.category');
b221dc6f 935 foreach ($this->visiblecolumns as $column) {
e4d1d5e0 936 $fields = array_merge($fields, $column->get_required_fields());
b221dc6f 937 }
938 $fields = array_unique($fields);
939
940 /// Build the order by clause.
941 $sorts = array();
942 foreach ($this->sort as $sort => $order) {
943 list($colname, $subsort) = $this->parse_subsort($sort);
944 $sorts[] = $this->knowncolumntypes[$colname]->sort_expression($order < 0, $subsort);
945 }
946
e4d1d5e0 947 /// Build the where clause.
948 $tests = array('parent = 0');
949
950 if ($showhidden) {
951 $tests[] = 'hidden = 0';
952 }
953
954 if ($recurse) {
955 $categoryids = explode(',', question_categorylist($category->id));
956 } else {
957 $categoryids = array($category->id);
958 }
959 list($catidtest, $params) = $DB->get_in_or_equal($categoryids, SQL_PARAMS_NAMED, 'cat0000');
960 $tests[] = 'q.category ' . $catidtest;
961 $this->sqlparams = $params;
962
b221dc6f 963 /// Build the SQL.
964 $sql = ' FROM {question} q ' . implode(' ', $joins);
e4d1d5e0 965 $sql .= ' WHERE ' . implode(' AND ', $tests);
b221dc6f 966 $this->countsql = 'SELECT count(1)' . $sql;
e4d1d5e0 967 $this->loadsql = 'SELECT ' . implode(', ', $fields) . $sql . ' ORDER BY ' . implode(', ', $sorts);
968 $this->sqlparams = $params;
5bd22790 969 }
970
e4d1d5e0 971 protected function get_question_count() {
972 global $DB;
973 return $DB->count_records_sql($this->countsql, $this->sqlparams);
974 }
975
976 protected function load_page_questions($page, $perpage) {
977 global $DB;
978 $questions = $DB->get_recordset_sql($this->loadsql, $this->sqlparams, $page*$perpage, $perpage);
979 if (!$questions->valid()) {
980 /// No questions on this page. Reset to page 0.
981 $questions = $DB->get_recordset_sql($this->loadsql, $this->sqlparams, 0, $perpage);
982 }
983 return $questions;
984 }
985
986 public function base_url() {
987 return $this->baseurl;
5bd22790 988 }
989
990 public function edit_question_url($questionid) {
991 return $this->editquestionurl->out(false, array('id' => $questionid));
992 }
993
e4d1d5e0 994 public function move_question_url($questionid) {
995 return $this->editquestionurl->out(false, array('id' => $questionid, 'movecontext' => 1));
996 }
997
5bd22790 998 public function preview_question_url($questionid) {
999 global $CFG;
e4d1d5e0 1000 return $CFG->wwwroot . '/question/preview.php?id=' . $questionid . '&amp;course=' . $this->course->id;
f4b879dd 1001 }
516cf3eb 1002
f4b879dd 1003 /**
1004 * Shows the question bank editing interface.
1005 *
1006 * The function also processes a number of actions:
1007 *
1008 * Actions affecting the question pool:
1009 * move Moves a question to a different category
1010 * deleteselected Deletes the selected questions from the category
1011 * Other actions:
1012 * category Chooses the category
1013 * displayoptions Sets display options
f4b879dd 1014 */
5bd22790 1015 public function display($tabname, $page, $perpage, $sortorder,
f4b879dd 1016 $sortorderdecoded, $cat, $recurse, $showhidden, $showquestiontext){
f4b879dd 1017
5bd22790 1018 if ($this->process_actions_needing_ui()) {
5b5e5ab2 1019 return;
f4b879dd 1020 }
516cf3eb 1021
5b5e5ab2 1022 // Category selection form
f4b879dd 1023 print_box_start('generalbox questionbank');
1024 print_heading(get_string('questionbank', 'question'), '', 2);
5b5e5ab2 1025
5bd22790 1026 $this->display_category_form($this->contexts->having_one_edit_tab_cap($tabname),
971c6fca 1027 $this->baseurl, $cat);
1028 $this->display_options($recurse, $showhidden, $showquestiontext);
1029
1030 if (!$category = $this->get_current_category($cat)) {
1031 return;
1032 }
1033 $this->print_category_info($category);
624cbc9c 1034
f4b879dd 1035 // continues with list of questions
5bd22790 1036 $this->display_question_list($this->contexts->having_one_edit_tab_cap($tabname), $this->baseurl, $cat, $this->cm,
f4b879dd 1037 $recurse, $page, $perpage, $showhidden, $sortorder, $sortorderdecoded, $showquestiontext,
5bd22790 1038 $this->contexts->having_cap('moodle/question:add'));
516cf3eb 1039
f4b879dd 1040 print_box_end();
516cf3eb 1041 }
1042
971c6fca 1043 protected function print_choose_category_message($categoryandcontext) {
1044 echo "<p style=\"text-align:center;\"><b>";
1045 print_string("selectcategoryabove", "quiz");
1046 echo "</b></p>";
1047 }
1048
1049 protected function get_current_category($categoryandcontext) {
1050 global $DB;
1051 list($categoryid, $contextid) = explode(',', $categoryandcontext);
1052 if (!$categoryid) {
1053 $this->print_choose_category_message($categoryandcontext);
1054 return false;
1055 }
1056
1057 if (!$category = $DB->get_record('question_categories',
1058 array('id' => $categoryid, 'contextid' => $contextid))) {
1059 print_box_start('generalbox questionbank');
1060 notify('Category not found!');
1061 print_box_end();
1062 return false;
1063 }
1064
1065 return $category;
1066 }
1067
1068 protected function print_category_info($category) {
1069 $formatoptions = new stdClass;
1070 $formatoptions->noclean = true;
1071 echo '<div class="boxaligncenter">';
1072 echo format_text($category->info, FORMAT_MOODLE, $formatoptions, $this->course->id);
1073 echo "</div>\n";
1074 }
1075
f4b879dd 1076 /**
1077 * prints a form to choose categories
1078 */
971c6fca 1079 protected function display_category_form($contexts, $pageurl, $current) {
f4b879dd 1080 global $CFG;
516cf3eb 1081
f4b879dd 1082 /// Get all the existing categories now
1083 $catmenu = question_category_options($contexts, false, 0, true);
516cf3eb 1084
971c6fca 1085 $strcategory = get_string('selectcategory', 'quiz');
f4b879dd 1086 $strshow = get_string('show', 'quiz');
1087 $streditcats = get_string('editcategories', 'quiz');
1088
5b5e5ab2 1089 popup_form('edit.php?'.$pageurl->get_query_string().'&amp;category=',
1090 $catmenu, 'catmenu', $current, '', '', '', false, 'self',
971c6fca 1091 $strcategory);
1092 }
f4b879dd 1093
971c6fca 1094 protected function display_options($recurse = 1, $showhidden = false, $showquestiontext = false) {
f4b879dd 1095 echo '<form method="get" action="edit.php" id="displayoptions">';
1096 echo "<fieldset class='invisiblefieldset'>";
971c6fca 1097 echo $this->baseurl->hidden_params_out(array('recurse', 'showhidden', 'showquestiontext'));
f4b879dd 1098 $this->display_category_form_checkbox('recurse', $recurse);
1099 $this->display_category_form_checkbox('showhidden', $showhidden);
1100 $this->display_category_form_checkbox('showquestiontext', $showquestiontext);
1101 echo '<noscript><div class="centerpara"><input type="submit" value="'. get_string('go') .'" />';
1102 echo '</div></noscript></fieldset></form>';
516cf3eb 1103 }
1104
f4b879dd 1105 /**
971c6fca 1106 * Print a single option checkbox. Used by the preceeding.
f4b879dd 1107 */
1108 protected function display_category_form_checkbox($name, $checked) {
1109 echo '<div><input type="hidden" id="' . $name . '_off" name="' . $name . '" value="0" />';
1110 echo '<input type="checkbox" id="' . $name . '_on" name="' . $name . '" value="1"';
1111 if ($checked) {
1112 echo ' checked="checked"';
516cf3eb 1113 }
f4b879dd 1114 echo ' onchange="getElementById(\'displayoptions\').submit(); return true;" />';
1115 echo '<label for="' . $name . '_on">';
1116 print_string($name, 'quiz');
1117 echo "</label></div>\n";
516cf3eb 1118 }
1119
e4d1d5e0 1120 protected function create_new_question_form($category, $canadd) {
1121 $qtypemenu = question_type_menu();
1122 $straddquestions = get_string('addquestions', 'quiz');
1123 echo '<div class="createnewquestion">';
1124 if ($canadd) {
1125 popup_form($this->editquestionurl->out(false, array('category' => $category->id)) . '&amp;qtype=',
1126 $qtypemenu, 'addquestion', '', 'choose', '', '', false, 'self', $straddquestions);
1127 helpbutton('questiontypes', $straddquestions, 'quiz');
1128 } else {
1129 print_string('nopermissionadd', 'question');
1130 }
1131 echo '</div>';
1132 }
1133
f4b879dd 1134 /**
1135 * Prints the table of questions in a category with interactions
1136 *
1137 * @param object $course The course object
1138 * @param int $categoryid The id of the question category to be displayed
1139 * @param int $cm The course module record if we are in the context of a particular module, 0 otherwise
1140 * @param int $recurse This is 1 if subcategories should be included, 0 otherwise
1141 * @param int $page The number of the page to be displayed
1142 * @param int $perpage Number of questions to show per page
1143 * @param boolean $showhidden True if also hidden questions should be displayed
1144 * @param boolean $showquestiontext whether the text of each question should be shown in the list
1145 */
5bd22790 1146 protected function display_question_list($contexts, $pageurl, $categoryandcontext,
5b5e5ab2 1147 $cm = null, $recurse=1, $page=0, $perpage=100, $showhidden=false,
1148 $sortorder='typename', $sortorderdecoded='qtype, name ASC',
f4b879dd 1149 $showquestiontext = false, $addcontexts = array()) {
971c6fca 1150 global $CFG, $DB;
f4b879dd 1151
e4d1d5e0 1152 $category = $this->get_current_category($categoryandcontext);
f4b879dd 1153
971c6fca 1154 $cmoptions = new stdClass;
1155 $cmoptions->hasattempts = !empty($this->quizhasattempts);
1156
f4b879dd 1157 $strselectall = get_string("selectall", "quiz");
1158 $strselectnone = get_string("selectnone", "quiz");
f4b879dd 1159 $strdelete = get_string("delete");
5b5e5ab2 1160
e4d1d5e0 1161 list($categoryid, $contextid) = explode(',', $categoryandcontext);
f4b879dd 1162 $catcontext = get_context_instance_by_id($contextid);
e4d1d5e0 1163
f4b879dd 1164 $canadd = has_capability('moodle/question:add', $catcontext);
f4b879dd 1165 $caneditall =has_capability('moodle/question:editall', $catcontext);
1166 $canuseall =has_capability('moodle/question:useall', $catcontext);
1167 $canmoveall =has_capability('moodle/question:moveall', $catcontext);
1168
e4d1d5e0 1169 $this->create_new_question_form($category, $canadd);
f4b879dd 1170
e4d1d5e0 1171 $this->build_query_sql($category, $recurse, $showhidden);
1172 $totalnumber = $this->get_question_count();
1173 if ($totalnumber == 0) {
f4b879dd 1174 return;
271e6dec 1175 }
1176
e4d1d5e0 1177 $questions = $this->load_page_questions($page, $perpage);
5b5e5ab2 1178
1179 echo '<div class="categorypagingbarcontainer">';
1180 print_paging_bar($totalnumber, $page, $perpage, $pageurl, 'qpage');
1181 echo '</div>';
f4b879dd 1182
1183 echo '<form method="post" action="edit.php">';
1184 echo '<fieldset class="invisiblefieldset" style="display: block;">';
1185 echo '<input type="hidden" name="sesskey" value="'.sesskey().'" />';
1186 echo $pageurl->hidden_params_out();
5b5e5ab2 1187 echo '<div class="categoryquestionscontainer">';
f4b879dd 1188
e4d1d5e0 1189 $this->start_table();
f4b879dd 1190 foreach ($questions as $question) {
e4d1d5e0 1191 $this->print_table_row($question);
271e6dec 1192 }
e4d1d5e0 1193 $this->end_table();
86909ce0 1194
5b5e5ab2 1195 echo '<div class="categorypagingbarcontainer pagingbottom">';
f4b879dd 1196 $paging = print_paging_bar($totalnumber, $page, $perpage, $pageurl, 'qpage', false, true);
1197 if ($totalnumber > DEFAULT_QUESTIONS_PER_PAGE) {
1198 if ($perpage == DEFAULT_QUESTIONS_PER_PAGE) {
1199 $showall = '<a href="edit.php?'.$pageurl->get_query_string(array('qperpage'=>1000)).'">'.get_string('showall', 'moodle', $totalnumber).'</a>';
1200 } else {
1201 $showall = '<a href="edit.php?'.$pageurl->get_query_string(array('qperpage'=>DEFAULT_QUESTIONS_PER_PAGE)).'">'.get_string('showperpage', 'moodle', DEFAULT_QUESTIONS_PER_PAGE).'</a>';
1202 }
1203 if ($paging) {
1204 $paging = substr($paging, 0, strrpos($paging, '</div>'));
1205 $paging .= "<br />$showall</div>";
1206 } else {
1207 $paging = "<div class='paging'>$showall</div>";
1208 }
86909ce0 1209 }
f4b879dd 1210 echo $paging;
5b5e5ab2 1211 echo '</div>';
f4b879dd 1212
5b5e5ab2 1213 echo '<div class="categoryselectallcontainer">';
f4b879dd 1214 if ($caneditall || $canmoveall || $canuseall){
1215 echo '<a href="javascript:select_all_in(\'TABLE\',null,\'categoryquestions\');">'.$strselectall.'</a> /'.
1216 ' <a href="javascript:deselect_all_in(\'TABLE\',null,\'categoryquestions\');">'.$strselectnone.'</a>';
1217 echo '<br />';
5b5e5ab2 1218 }
1219 echo "</div>\n";
1220
1221 echo '<div class="modulespecificbuttonscontainer">';
1222 if ($caneditall || $canmoveall || $canuseall){
f4b879dd 1223 echo '<strong>&nbsp;'.get_string('withselected', 'quiz').':</strong><br />';
1224
1225 if (function_exists('module_specific_buttons')) {
971c6fca 1226 echo module_specific_buttons($this->cm->id,$cmoptions);
f4b879dd 1227 }
5b5e5ab2 1228
f4b879dd 1229 // print delete and move selected question
1230 if ($caneditall) {
5b5e5ab2 1231 echo '<input type="submit" name="deleteselected" value="' . $strdelete . "\" />\n";
f4b879dd 1232 }
5b5e5ab2 1233
f4b879dd 1234 if ($canmoveall && count($addcontexts)) {
1235 echo '<input type="submit" name="move" value="'.get_string('moveto', 'quiz')."\" />\n";
1236 question_category_select_menu($addcontexts, false, 0, "$category->id,$category->contextid");
1237 }
1238
1239 if (function_exists('module_specific_controls') && $canuseall) {
971c6fca 1240 $modulespecific = module_specific_controls($totalnumber, $recurse, $category, $this->cm->id,$cmoptions);
5b5e5ab2 1241 if(!empty($modulespecific)){
1242 echo "<hr />$modulespecific";
1243 }
271e6dec 1244 }
1245 }
5b5e5ab2 1246 echo "</div>\n";
1247
f4b879dd 1248 echo '</fieldset>';
1249 echo "</form>\n";
1250 }
1251
e4d1d5e0 1252 protected function start_table() {
1253 echo '<table id="categoryquestions">' . "\n";
1254 echo "<thead>\n";
1255 $this->print_table_headers();
1256 echo "</thead>\n";
1257 echo "<tbody>\n";
1258 }
1259
1260 protected function end_table() {
1261 echo "</tbody>\n";
1262 echo "</table>\n";
1263 }
1264
1265 protected function print_table_headers() {
1266 echo "<tr>\n";
1267 foreach ($this->visiblecolumns as $column) {
1268 $column->display_header();
1269 }
1270 echo "</tr>\n";
1271 }
1272
1273 protected function get_row_classes($question) {
1274 $classes = array();
1275 if ($question->hidden) {
1276 $classes[] = 'dimmed_text';
1277 }
1278 return $classes;
1279 }
1280
1281 protected function print_table_row($question) {
1282 $rowclasses = implode(' ', $this->get_row_classes($question));
1283 if ($rowclasses) {
1284 echo '<tr class="' . $rowclasses . '">' . "\n";
1285 } else {
1286 echo "<tr>\n";
1287 }
1288 foreach ($this->visiblecolumns as $column) {
1289 $column->display($question, $rowclasses);
1290 }
1291 echo "</tr>\n";
1292 }
1293
5bd22790 1294 protected function display_question_sort_options($pageurl, $sortorder){
f4b879dd 1295 //sort options
1296 $html = "<div class=\"mdl-align questionsortoptions\">";
1297 // POST method should only be used for parameters that change data
1298 // or if POST method has to be used, the user must be redirected immediately to
1299 // non-POSTed page to not break the back button
1300 $html .= '<form method="get" action="edit.php">';
1301 $html .= '<fieldset class="invisiblefieldset" style="display: block;">';
1302 $html .= '<input type="hidden" name="sesskey" value="'.sesskey().'" />';
1303 $html .= $pageurl->hidden_params_out(array('qsortorder'));
1304 //choose_from_menu concatenates the form name with
1305 //"menu" so the label is for menuqsortorder
1306 $sortoptions = array('alpha' => get_string("qname", "quiz"),
1307 'typealpha' => get_string("qtypename", "quiz"),
1308 'age' => get_string("age", "quiz"));
1309 $a = choose_from_menu($sortoptions, 'qsortorder', $sortorder, false, 'this.form.submit();', '0', true);
1310 $html .= '<label for="menuqsortorder">'.get_string('sortquestionsbyx', 'quiz', $a).'</label>';
1311 $html .= '<noscript><div><input type="submit" value="'.get_string("sortsubmit", "quiz").'" /></div></noscript>';
1312 $html .= '</fieldset>';
1313 $html .= "</form>\n";
1314 $html .= "</div>\n";
1315 echo $html;
1316 }
1317
5bd22790 1318 public function process_actions() {
971c6fca 1319 global $CFG, $DB;
f4b879dd 1320 /// Now, check for commands on this page and modify variables as necessary
1321 if (optional_param('move', false, PARAM_BOOL) and confirm_sesskey()) { /// Move selected questions to new category
1322 $category = required_param('category', PARAM_SEQUENCE);
1323 list($tocategoryid, $contextid) = explode(',', $category);
1324 if (! $tocategory = $DB->get_record('question_categories', array('id' => $tocategoryid, 'contextid' => $contextid))) {
1325 print_error('cannotfindcate', 'question');
271e6dec 1326 }
f4b879dd 1327 $tocontext = get_context_instance_by_id($contextid);
1328 require_capability('moodle/question:add', $tocontext);
1329 $rawdata = (array) data_submitted();
1330 $questionids = array();
1331 foreach ($rawdata as $key => $value) { // Parse input for question ids
1332 if (preg_match('!^q([0-9]+)$!', $key, $matches)) {
1333 $key = $matches[1];
1334 $questionids[] = $key;
271e6dec 1335 }
1336 }
f4b879dd 1337 if ($questionids){
1338 list($usql, $params) = $DB->get_in_or_equal($questionids);
1339 $sql = "SELECT q.*, c.contextid FROM {question} q, {question_categories} c WHERE q.id $usql AND c.id = q.category";
1340 if (!$questions = $DB->get_records_sql($sql, $params)){
1341 print_error('questiondoesnotexist', 'question', $pageurl->out());
271e6dec 1342 }
f4b879dd 1343 $checkforfiles = false;
1344 foreach ($questions as $question){
1345 //check capabilities
1346 question_require_capability_on($question, 'move');
1347 $fromcontext = get_context_instance_by_id($question->contextid);
1348 if (get_filesdir_from_context($fromcontext) != get_filesdir_from_context($tocontext)){
1349 $checkforfiles = true;
1350 }
1351 }
1352 $returnurl = $pageurl->out(false, array('category'=>"$tocategoryid,$contextid"));
1353 if (!$checkforfiles){
1354 if (!question_move_questions_to_category(implode(',', $questionids), $tocategory->id)) {
1355 print_error('errormovingquestions', 'question', $returnurl, $questionids);
1356 }
1357 redirect($returnurl);
271e6dec 1358 } else {
f4b879dd 1359 $movecontexturl = new moodle_url($CFG->wwwroot.'/question/contextmoveq.php',
1360 array('returnurl' => $returnurl,
1361 'ids'=>$questionidlist,
1362 'tocatid'=> $tocategoryid));
1363 if ($cm){
1364 $movecontexturl->param('cmid', $cm->id);
1365 } else {
971c6fca 1366 $movecontexturl->param('courseid', $this->course->id);
f4b879dd 1367 }
1368 redirect($movecontexturl->out());
86909ce0 1369 }
1370 }
1371 }
86909ce0 1372
f4b879dd 1373 if (optional_param('deleteselected', false, PARAM_BOOL)) { // delete selected questions from the category
1374 if (($confirm = optional_param('confirm', '', PARAM_ALPHANUM)) and confirm_sesskey()) { // teacher has already confirmed the action
1375 $deleteselected = required_param('deleteselected');
1376 if ($confirm == md5($deleteselected)) {
1377 if ($questionlist = explode(',', $deleteselected)) {
1378 // for each question either hide it if it is in use or delete it
1379 foreach ($questionlist as $questionid) {
1380 question_require_capability_on($questionid, 'edit');
1381 if ($DB->record_exists('quiz_question_instances', array('question' => $questionid))) {
1382 if (!$DB->set_field('question', 'hidden', 1, array('id' => $questionid))) {
1383 question_require_capability_on($questionid, 'edit');
1384 print_error('cannothidequestion', 'question');
1385 }
1386 } else {
1387 delete_question($questionid);
86909ce0 1388 }
86909ce0 1389 }
1390 }
f4b879dd 1391 redirect($pageurl->out());
1392 } else {
1393 print_error('invalidconfirm', 'question');
86909ce0 1394 }
86909ce0 1395 }
86909ce0 1396 }
8e77884c 1397
f4b879dd 1398 // Unhide a question
1399 if(($unhide = optional_param('unhide', '', PARAM_INT)) and confirm_sesskey()) {
1400 question_require_capability_on($unhide, 'edit');
1401 if(!$DB->set_field('question', 'hidden', 0, array('id', $unhide))) {
1402 print_error('cannotunhidequestion', 'question');
271e6dec 1403 }
271e6dec 1404 redirect($pageurl->out());
1405 }
271e6dec 1406 }
5bd22790 1407
1408 public function process_actions_needing_ui() {
e4d1d5e0 1409 global $DB;
5bd22790 1410 if (optional_param('deleteselected', false, PARAM_BOOL)) {
1411 // make a list of all the questions that are selected
1412 $rawquestions = $_REQUEST; // This code is called by both POST forms and GET links, so cannot use data_submitted.
1413 $questionlist = ''; // comma separated list of ids of questions to be deleted
1414 $questionnames = ''; // string with names of questions separated by <br /> with
1415 // an asterix in front of those that are in use
1416 $inuse = false; // set to true if at least one of the questions is in use
1417 foreach ($rawquestions as $key => $value) { // Parse input for question ids
1418 if (preg_match('!^q([0-9]+)$!', $key, $matches)) {
1419 $key = $matches[1];
1420 $questionlist .= $key.',';
1421 question_require_capability_on($key, 'edit');
1422 if ($DB->record_exists('quiz_question_instances', array('question' => $key))) {
1423 $questionnames .= '* ';
1424 $inuse = true;
1425 }
1426 $questionnames .= $DB->get_field('question', 'name', array('id' => $key)) . '<br />';
1427 }
1428 }
1429 if (!$questionlist) { // no questions were selected
1430 redirect($this->baseurl->out());
1431 }
1432 $questionlist = rtrim($questionlist, ',');
1433
1434 // Add an explanation about questions in use
1435 if ($inuse) {
1436 $questionnames .= '<br />'.get_string('questionsinuse', 'quiz');
1437 }
1438 notice_yesno(get_string("deletequestionscheck", "quiz", $questionnames),
e4d1d5e0 1439 $this->baseurl->out_action(array('deleteselected'=>$questionlist, 'confirm'=>md5($questionlist))),
1440 $this->baseurl->out_action());
5bd22790 1441
1442 return true;
1443 }
1444 }
86909ce0 1445}
f4b879dd 1446
b72ff476 1447/**
1448 * Common setup for all pages for editing questions.
271e6dec 1449 * @param string $edittab code for this edit tab
b72ff476 1450 * @param boolean $requirecmid require cmid? default false
1451 * @param boolean $requirecourseid require courseid, if cmid is not given? default true
271e6dec 1452 * @return array $thispageurl, $contexts, $cmid, $cm, $module, $pagevars
b72ff476 1453 */
271e6dec 1454function question_edit_setup($edittab, $requirecmid = false, $requirecourseid = true){
971c6fca 1455 global $QUESTION_EDITTABCAPS, $DB;
271e6dec 1456
1457 //$thispageurl is used to construct urls for all question edit pages we link to from this page. It contains an array
36e298bc 1458 //of parameters that are passed from page to page.
b72ff476 1459 $thispageurl = new moodle_url();
b4a2e413 1460 $thispageurl->remove_params(); // We are going to explicity add back everything important - this avoids unwanted params from being retained.
1461
b72ff476 1462 if ($requirecmid){
1463 $cmid =required_param('cmid', PARAM_INT);
1464 } else {
1465 $cmid = optional_param('cmid', 0, PARAM_INT);
1466 }
1467 if ($cmid){
271e6dec 1468 list($module, $cm) = get_module_from_cmid($cmid);
b72ff476 1469 $courseid = $cm->course;
1470 $thispageurl->params(compact('cmid'));
271e6dec 1471 require_login($courseid, false, $cm);
1472 $thiscontext = get_context_instance(CONTEXT_MODULE, $cmid);
b72ff476 1473 } else {
1474 $module = null;
1475 $cm = null;
1476 if ($requirecourseid){
1477 $courseid = required_param('courseid', PARAM_INT);
1478 } else {
1479 $courseid = optional_param('courseid', 0, PARAM_INT);
1480 }
1481 if ($courseid){
1482 $thispageurl->params(compact('courseid'));
271e6dec 1483 require_login($courseid, false);
1484 $thiscontext = get_context_instance(CONTEXT_COURSE, $courseid);
1485 } else {
1486 $thiscontext = null;
b72ff476 1487 }
1488 }
271e6dec 1489
1490 if ($thiscontext){
1491 $contexts = new question_edit_contexts($thiscontext);
1492 $contexts->require_one_edit_tab_cap($edittab);
1493
1494 } else {
1495 $contexts = null;
1496 }
1497
1498
1499
36e298bc 1500 $pagevars['qpage'] = optional_param('qpage', -1, PARAM_INT);
271e6dec 1501
7bc26c8f 1502 //pass 'cat' from page to page and when 'category' comes from a drop down menu
271e6dec 1503 //then we also reset the qpage so we go to page 1 of
7bc26c8f 1504 //a new cat.
271e6dec 1505 $pagevars['cat'] = optional_param('cat', 0, PARAM_SEQUENCE);// if empty will be set up later
1506 if ($category = optional_param('category', 0, PARAM_SEQUENCE)){
a18fbcfb 1507 if ($pagevars['cat'] != $category){ // is this a move to a new category?
1508 $pagevars['cat'] = $category;
1509 $pagevars['qpage'] = 0;
1510 }
7bc26c8f 1511 }
1512 if ($pagevars['cat']){
1513 $thispageurl->param('cat', $pagevars['cat']);
1514 }
b72ff476 1515 if ($pagevars['qpage'] > -1) {
1516 $thispageurl->param('qpage', $pagevars['qpage']);
1517 } else {
1518 $pagevars['qpage'] = 0;
1519 }
1520
36e298bc 1521 $pagevars['qperpage'] = optional_param('qperpage', -1, PARAM_INT);
b72ff476 1522 if ($pagevars['qperpage'] > -1) {
1523 $thispageurl->param('qperpage', $pagevars['qperpage']);
1524 } else {
1525 $pagevars['qperpage'] = DEFAULT_QUESTIONS_PER_PAGE;
1526 }
271e6dec 1527
36e298bc 1528 $sortoptions = array('alpha' => 'name, qtype ASC',
1529 'typealpha' => 'qtype, name ASC',
1530 'age' => 'id ASC');
1531
1532 if ($sortorder = optional_param('qsortorder', '', PARAM_ALPHA)) {
1533 $pagevars['qsortorderdecoded'] = $sortoptions[$sortorder];
1534 $pagevars['qsortorder'] = $sortorder;
1535 $thispageurl->param('qsortorder', $sortorder);
b72ff476 1536 } else {
7bc26c8f 1537 $pagevars['qsortorderdecoded'] = $sortoptions['typealpha'];
1538 $pagevars['qsortorder'] = 'typealpha';
271e6dec 1539 }
36e298bc 1540
271e6dec 1541 $defaultcategory = question_make_default_categories($contexts->all());
1542
1543 $contextlistarr = array();
1544 foreach ($contexts->having_one_edit_tab_cap($edittab) as $context){
1545 $contextlistarr[] = "'$context->id'";
1546 }
1547 $contextlist = join($contextlistarr, ' ,');
1548 if (!empty($pagevars['cat'])){
1549 $catparts = explode(',', $pagevars['cat']);
f34488b2 1550 if (!$catparts[0] || (FALSE !== array_search($catparts[1], $contextlistarr)) ||
1551 !$DB->count_records_select("question_categories", "id = ? AND contextid = ?", array($catparts[0], $catparts[1]))) {
5a2a5331 1552 print_error('invalidcategory', 'quiz');
271e6dec 1553 }
1554 } else {
1555 $category = $defaultcategory;
1556 $pagevars['cat'] = "$category->id,$category->contextid";
36e298bc 1557 }
1558
1559 if(($recurse = optional_param('recurse', -1, PARAM_BOOL)) != -1) {
1560 $pagevars['recurse'] = $recurse;
1561 $thispageurl->param('recurse', $recurse);
1562 } else {
1563 $pagevars['recurse'] = 1;
1564 }
271e6dec 1565
36e298bc 1566 if(($showhidden = optional_param('showhidden', -1, PARAM_BOOL)) != -1) {
1567 $pagevars['showhidden'] = $showhidden;
1568 $thispageurl->param('showhidden', $showhidden);
1569 } else {
1570 $pagevars['showhidden'] = 0;
1571 }
271e6dec 1572
36e298bc 1573 if(($showquestiontext = optional_param('showquestiontext', -1, PARAM_BOOL)) != -1) {
1574 $pagevars['showquestiontext'] = $showquestiontext;
1575 $thispageurl->param('showquestiontext', $showquestiontext);
1576 } else {
1577 $pagevars['showquestiontext'] = 0;
1578 }
271e6dec 1579
986effb6 1580 //category list page
1581 $pagevars['cpage'] = optional_param('cpage', 1, PARAM_INT);
1582 if ($pagevars['cpage'] != 1){
1583 $thispageurl->param('cpage', $pagevars['cpage']);
1584 }
36e298bc 1585
271e6dec 1586
1587 return array($thispageurl, $contexts, $cmid, $cm, $module, $pagevars);
1588}
1589class question_edit_contexts{
1590 var $allcontexts;
1591 /**
1592 * @param current context
1593 */
1594 function question_edit_contexts($thiscontext){
1595 $pcontextids = get_parent_contexts($thiscontext);
1596 $contexts = array($thiscontext);
1597 foreach ($pcontextids as $pcontextid){
1598 $contexts[] = get_context_instance_by_id($pcontextid);
1599 }
1600 $this->allcontexts = $contexts;
1601 }
1602 /**
1603 * @return array all parent contexts
1604 */
1605 function all(){
1606 return $this->allcontexts;
1607 }
1608 /**
1609 * @return object lowest context which must be either the module or course context
1610 */
1611 function lowest(){
1612 return $this->allcontexts[0];
1613 }
1614 /**
1615 * @param string $cap capability
1616 * @return array parent contexts having capability, zero based index
1617 */
1618 function having_cap($cap){
1619 $contextswithcap = array();
1620 foreach ($this->allcontexts as $context){
1621 if (has_capability($cap, $context)){
1622 $contextswithcap[] = $context;
1623 }
1624 }
1625 return $contextswithcap;
1626 }
1627 /**
1628 * @param array $caps capabilities
1629 * @return array parent contexts having at least one of $caps, zero based index
1630 */
1631 function having_one_cap($caps){
1632 $contextswithacap = array();
1633 foreach ($this->allcontexts as $context){
1634 foreach ($caps as $cap){
1635 if (has_capability($cap, $context)){
1636 $contextswithacap[] = $context;
1637 break; //done with caps loop
1638 }
1639 }
1640 }
1641 return $contextswithacap;
1642 }
1643 /**
1644 * @param string $tabname edit tab name
1645 * @return array parent contexts having at least one of $caps, zero based index
1646 */
1647 function having_one_edit_tab_cap($tabname){
1648 global $QUESTION_EDITTABCAPS;
1649 return $this->having_one_cap($QUESTION_EDITTABCAPS[$tabname]);
1650 }
1651 /**
1652 * Has at least one parent context got the cap $cap?
1653 *
1654 * @param string $cap capability
1655 * @return boolean
1656 */
1657 function have_cap($cap){
1658 return (count($this->having_cap($cap)));
1659 }
1660
1661 /**
1662 * Has at least one parent context got one of the caps $caps?
1663 *
1664 * @param string $cap capability
1665 * @return boolean
1666 */
1667 function have_one_cap($caps){
1668 foreach ($caps as $cap){
1669 if ($this->have_cap($cap)){
1670 return true;
1671 }
1672 }
1673 return false;
1674 }
1675 /**
1676 * Has at least one parent context got one of the caps for actions on $tabname
1677 *
1678 * @param string $tabname edit tab name
1679 * @return boolean
1680 */
1681 function have_one_edit_tab_cap($tabname){
1682 global $QUESTION_EDITTABCAPS;
1683 return $this->have_one_cap($QUESTION_EDITTABCAPS[$tabname]);
1684 }
1685 /**
1686 * Throw error if at least one parent context hasn't got the cap $cap
1687 *
1688 * @param string $cap capability
1689 */
1690 function require_cap($cap){
1691 if (!$this->have_cap($cap)){
1692 print_error('nopermissions', '', '', $cap);
1693 }
1694 }
1695 /**
1696 * Throw error if at least one parent context hasn't got one of the caps $caps
1697 *
1698 * @param array $cap capabilities
1699 */
1700 function require_one_cap($caps){
1701 if (!$this->have_one_cap($caps)){
1702 $capsstring = join($caps, ', ');
1703 print_error('nopermissions', '', '', $capsstring);
1704 }
1705 }
1706 /**
1707 * Throw error if at least one parent context hasn't got one of the caps $caps
1708 *
1709 * @param string $tabname edit tab name
1710 */
1711 function require_one_edit_tab_cap($tabname){
1712 if (!$this->have_one_edit_tab_cap($tabname)){
1713 print_error('nopermissions', '', '', 'access question edit tab '.$tabname);
1714 }
1715 }
1716}
1717
1718//capabilities for each page of edit tab.
1719//this determines which contexts' categories are available. At least one
1720//page is displayed if user has one of the capability on at least one context
1721$QUESTION_EDITTABCAPS = array(
a856c14e 1722 'editq' => array('moodle/question:add',
1723 'moodle/question:editmine',
1724 'moodle/question:editall',
1725 'moodle/question:viewmine',
1726 'moodle/question:viewall',
1727 'moodle/question:usemine',
1728 'moodle/question:useall',
1729 'moodle/question:movemine',
1730 'moodle/question:moveall'),
1731 'questions'=>array('moodle/question:add',
1732 'moodle/question:editmine',
1733 'moodle/question:editall',
1734 'moodle/question:viewmine',
1735 'moodle/question:viewall',
1736 'moodle/question:movemine',
1737 'moodle/question:moveall'),
1738 'categories'=>array('moodle/question:managecategory'),
1739 'import'=>array('moodle/question:add'),
1740 'export'=>array('moodle/question:viewall', 'moodle/question:viewmine'));
271e6dec 1741
1742/**
1743 * Make sure user is logged in as required in this context.
1744 */
1745function require_login_in_context($contextorid = null){
f34488b2 1746 global $DB;
271e6dec 1747 if (!is_object($contextorid)){
1748 $context = get_context_instance_by_id($contextorid);
1749 } else {
1750 $context = $contextorid;
1751 }
1752 if ($context && ($context->contextlevel == CONTEXT_COURSE)) {
1753 require_login($context->instanceid);
1754 } else if ($context && ($context->contextlevel == CONTEXT_MODULE)) {
f34488b2 1755 if ($cm = $DB->get_record('course_modules',array('id' =>$context->instanceid))) {
1756 if (!$course = $DB->get_record('course', array('id' => $cm->course))) {
0be2c858 1757 print_error('invalidcourseid');
271e6dec 1758 }
1759 require_course_login($course, true, $cm);
1760
1761 } else {
0be2c858 1762 print_error('invalidcoursemodule');
271e6dec 1763 }
1764 } else if ($context && ($context->contextlevel == CONTEXT_SYSTEM)) {
1765 if (!empty($CFG->forcelogin)) {
1766 require_login();
1767 }
1768
1769 } else {
1770 require_login();
1771 }
b72ff476 1772}
871ab9a3 1773?>