weekly release 2.4dev
[moodle.git] / question / engine / bank.php
CommitLineData
d1b7e03d 1<?php
d1b7e03d
TH
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/>.
16
d1b7e03d
TH
17/**
18 * More object oriented wrappers around parts of the Moodle question bank.
19 *
20 * In due course, I expect that the question bank will be converted to a
21 * fully object oriented structure, at which point this file can be a
22 * starting point.
23 *
017bc1d9 24 * @package moodlecore
d1b7e03d 25 * @subpackage questionbank
017bc1d9
TH
26 * @copyright 2009 The Open University
27 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
d1b7e03d
TH
28 */
29
30
a17b297d
TH
31defined('MOODLE_INTERNAL') || die();
32
afe24f85 33require_once(dirname(__FILE__) . '/../type/questiontypebase.php');
c468ce59 34
a17b297d 35
d1b7e03d
TH
36/**
37 * This static class provides access to the other question bank.
38 *
39 * It provides functions for managing question types and question definitions.
40 *
017bc1d9
TH
41 * @copyright 2009 The Open University
42 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
d1b7e03d
TH
43 */
44abstract class question_bank {
63637e9d
EL
45 // TODO: This limit can be deleted if someday we move all TEXTS to BIG ones. MDL-19603
46 const MAX_SUMMARY_LENGTH = 32000;
c83ed025 47
d1b7e03d
TH
48 /** @var array question type name => question_type subclass. */
49 private static $questiontypes = array();
50
51 /** @var array question type name => 1. Records which question definitions have been loaded. */
52 private static $loadedqdefs = array();
53
54 protected static $questionfinder = null;
55
56 /** @var boolean nasty hack to allow unit tests to call {@link load_question()}. */
57 private static $testmode = false;
58 private static $testdata = array();
59
f9b0500f
TH
60 private static $questionconfig = null;
61
af2f98ee
TH
62 /**
63 * @var array string => string The standard set of grade options (fractions)
64 * to use when editing questions, in the range 0 to 1 inclusive. Array keys
65 * are string becuase: a) we want grades to exactly 7 d.p., and b. you can't
66 * have float array keys in PHP.
67 * Initialised by {@link ensure_grade_options_initialised()}.
68 */
69 private static $fractionoptions = null;
70 /** @var array string => string The full standard set of (fractions) -1 to 1 inclusive. */
71 private static $fractionoptionsfull = null;
72
d649fb02
TH
73 /**
74 * @param string $qtypename a question type name, e.g. 'multichoice'.
75 * @return bool whether that question type is installed in this Moodle.
76 */
77 public static function is_qtype_installed($qtypename) {
78 $plugindir = get_plugin_directory('qtype', $qtypename);
79 return $plugindir && is_readable($plugindir . '/questiontype.php');
80 }
81
d1b7e03d
TH
82 /**
83 * Get the question type class for a particular question type.
84 * @param string $qtypename the question type name. For example 'multichoice' or 'shortanswer'.
f7970e3c 85 * @param bool $mustexist if false, the missing question type is returned when
d1b7e03d
TH
86 * the requested question type is not installed.
87 * @return question_type the corresponding question type class.
88 */
89 public static function get_qtype($qtypename, $mustexist = true) {
90 global $CFG;
91 if (isset(self::$questiontypes[$qtypename])) {
92 return self::$questiontypes[$qtypename];
93 }
f29aeb5a 94 $file = get_plugin_directory('qtype', $qtypename) . '/questiontype.php';
d1b7e03d
TH
95 if (!is_readable($file)) {
96 if ($mustexist || $qtypename == 'missingtype') {
88f0eb15 97 throw new coding_exception('Unknown question type ' . $qtypename);
d1b7e03d
TH
98 } else {
99 return self::get_qtype('missingtype');
100 }
101 }
102 include_once($file);
103 $class = 'qtype_' . $qtypename;
f29aeb5a
TH
104 if (!class_exists($class)) {
105 throw new coding_exception("Class $class must be defined in $file");
106 }
d1b7e03d
TH
107 self::$questiontypes[$qtypename] = new $class();
108 return self::$questiontypes[$qtypename];
109 }
110
f9b0500f
TH
111 /**
112 * Load the question configuration data from config_plugins.
113 * @return object get_config('question') with caching.
114 */
fde4560d 115 public static function get_config() {
f9b0500f 116 if (is_null(self::$questionconfig)) {
fde4560d 117 self::$questionconfig = get_config('question');
f9b0500f 118 }
fde4560d 119 return self::$questionconfig;
f9b0500f
TH
120 }
121
06f8ed54
TH
122 /**
123 * @param string $qtypename the internal name of a question type. For example multichoice.
f7970e3c 124 * @return bool whether users are allowed to create questions of this type.
06f8ed54
TH
125 */
126 public static function qtype_enabled($qtypename) {
f9b0500f
TH
127 $config = self::get_config();
128 $enabledvar = $qtypename . '_disabled';
129 return self::qtype_exists($qtypename) && empty($config->$enabledvar) &&
130 self::get_qtype($qtypename)->menu_name() != '';
131 }
132
133 /**
134 * @param string $qtypename the internal name of a question type. For example multichoice.
f7970e3c 135 * @return bool whether this question type exists.
f9b0500f
TH
136 */
137 public static function qtype_exists($qtypename) {
138 return array_key_exists($qtypename, get_plugin_list('qtype'));
06f8ed54
TH
139 }
140
d1b7e03d
TH
141 /**
142 * @param $qtypename the internal name of a question type, for example multichoice.
143 * @return string the human_readable name of this question type, from the language pack.
144 */
145 public static function get_qtype_name($qtypename) {
f9b0500f 146 return self::get_qtype($qtypename)->local_name();
d1b7e03d
TH
147 }
148
149 /**
150 * @return array all the installed question types.
151 */
152 public static function get_all_qtypes() {
153 $qtypes = array();
f29aeb5a
TH
154 foreach (get_plugin_list('qtype') as $plugin => $notused) {
155 try {
156 $qtypes[$plugin] = self::get_qtype($plugin);
2daffca5
TH
157 } catch (coding_exception $e) {
158 // Catching coding_exceptions here means that incompatible
159 // question types do not cause the rest of Moodle to break.
f29aeb5a 160 }
d1b7e03d
TH
161 }
162 return $qtypes;
163 }
164
f9b0500f 165 /**
d649fb02
TH
166 * Sort an array of question types according to the order the admin set up,
167 * and then alphabetically for the rest.
168 * @param array qtype->name() => qtype->local_name().
169 * @return array sorted array.
f9b0500f 170 */
d649fb02
TH
171 public static function sort_qtype_array($qtypes, $config = null) {
172 if (is_null($config)) {
173 $config = self::get_config();
174 }
f9b0500f
TH
175
176 $sortorder = array();
177 $otherqtypes = array();
d649fb02 178 foreach ($qtypes as $name => $localname) {
f9b0500f
TH
179 $sortvar = $name . '_sortorder';
180 if (isset($config->$sortvar)) {
181 $sortorder[$config->$sortvar] = $name;
182 } else {
d649fb02 183 $otherqtypes[$name] = $localname;
f9b0500f
TH
184 }
185 }
186
187 ksort($sortorder);
d609d962 188 collatorlib::asort($otherqtypes);
f9b0500f 189
d649fb02 190 $sortedqtypes = array();
f9b0500f 191 foreach ($sortorder as $name) {
d649fb02 192 $sortedqtypes[$name] = $qtypes[$name];
f9b0500f
TH
193 }
194 foreach ($otherqtypes as $name => $notused) {
d649fb02
TH
195 $sortedqtypes[$name] = $qtypes[$name];
196 }
197 return $sortedqtypes;
198 }
199
200 /**
201 * @return array all the question types that users are allowed to create,
202 * sorted into the preferred order set on the admin screen.
203 */
204 public static function get_creatable_qtypes() {
205 $config = self::get_config();
206 $allqtypes = self::get_all_qtypes();
207
208 $qtypenames = array();
209 foreach ($allqtypes as $name => $qtype) {
210 if (self::qtype_enabled($name)) {
211 $qtypenames[$name] = $qtype->local_name();
212 }
213 }
214
215 $qtypenames = self::sort_qtype_array($qtypenames);
216
217 $creatableqtypes = array();
218 foreach ($qtypenames as $name => $notused) {
f9b0500f
TH
219 $creatableqtypes[$name] = $allqtypes[$name];
220 }
a13d4fbd 221 return $creatableqtypes;
f9b0500f
TH
222 }
223
d1b7e03d
TH
224 /**
225 * Load the question definition class(es) belonging to a question type. That is,
226 * include_once('/question/type/' . $qtypename . '/question.php'), with a bit
227 * of checking.
228 * @param string $qtypename the question type name. For example 'multichoice' or 'shortanswer'.
229 */
230 public static function load_question_definition_classes($qtypename) {
231 global $CFG;
232 if (isset(self::$loadedqdefs[$qtypename])) {
233 return;
234 }
235 $file = $CFG->dirroot . '/question/type/' . $qtypename . '/question.php';
236 if (!is_readable($file)) {
88f0eb15 237 throw new coding_exception('Unknown question type (no definition) ' . $qtypename);
d1b7e03d
TH
238 }
239 include_once($file);
240 self::$loadedqdefs[$qtypename] = 1;
241 }
242
243 /**
244 * Load a question definition from the database. The object returned
245 * will actually be of an appropriate {@link question_definition} subclass.
f7970e3c 246 * @param int $questionid the id of the question to load.
9c197f44
TH
247 * @param bool $allowshuffle if false, then any shuffle option on the selected
248 * quetsion is disabled.
d1b7e03d
TH
249 * @return question_definition loaded from the database.
250 */
a31689a4 251 public static function load_question($questionid, $allowshuffle = true) {
c76145d3
TH
252 global $DB;
253
d1b7e03d
TH
254 if (self::$testmode) {
255 // Evil, test code in production, but now way round it.
256 return self::return_test_question_data($questionid);
257 }
258
56e82d99
TH
259 $questiondata = $DB->get_record_sql('
260 SELECT q.*, qc.contextid
261 FROM {question} q
262 JOIN {question_categories} qc ON q.category = qc.id
263 WHERE q.id = :id', array('id' => $questionid), MUST_EXIST);
d1b7e03d 264 get_question_options($questiondata);
a31689a4
TH
265 if (!$allowshuffle) {
266 $questiondata->options->shuffleanswers = false;
267 }
d1b7e03d
TH
268 return self::make_question($questiondata);
269 }
270
271 /**
272 * Convert the question information loaded with {@link get_question_options()}
273 * to a question_definintion object.
274 * @param object $questiondata raw data loaded from the database.
275 * @return question_definition loaded from the database.
276 */
277 public static function make_question($questiondata) {
278 return self::get_qtype($questiondata->qtype, false)->make_question($questiondata, false);
279 }
280
281 /**
282 * @return question_finder a question finder.
283 */
284 public static function get_finder() {
285 if (is_null(self::$questionfinder)) {
286 self::$questionfinder = new question_finder();
287 }
288 return self::$questionfinder;
289 }
290
291 /**
292 * Only to be called from unit tests. Allows {@link load_test_data()} to be used.
293 */
294 public static function start_unit_test() {
295 self::$testmode = true;
296 }
297
298 /**
299 * Only to be called from unit tests. Allows {@link load_test_data()} to be used.
300 */
301 public static function end_unit_test() {
302 self::$testmode = false;
303 self::$testdata = array();
304 }
305
306 private static function return_test_question_data($questionid) {
307 if (!isset(self::$testdata[$questionid])) {
88f0eb15 308 throw new coding_exception('question_bank::return_test_data(' . $questionid .
d1b7e03d
TH
309 ') called, but no matching question has been loaded by load_test_data.');
310 }
311 return self::$testdata[$questionid];
312 }
313
314 /**
315 * To be used for unit testing only. Will throw an exception if
316 * {@link start_unit_test()} has not been called first.
317 * @param object $questiondata a question data object to put in the test data store.
318 */
319 public static function load_test_question_data(question_definition $question) {
320 if (!self::$testmode) {
9c197f44
TH
321 throw new coding_exception('question_bank::load_test_data called when ' .
322 'not in test mode.');
d1b7e03d
TH
323 }
324 self::$testdata[$question->id] = $question;
325 }
af2f98ee 326
072db71c 327 protected static function ensure_fraction_options_initialised() {
af2f98ee
TH
328 if (!is_null(self::$fractionoptions)) {
329 return;
330 }
331
332 // define basic array of grades. This list comprises all fractions of the form:
333 // a. p/q for q <= 6, 0 <= p <= q
334 // b. p/10 for 0 <= p <= 10
335 // c. 1/q for 1 <= q <= 10
336 // d. 1/20
337 $rawfractions = array(
338 0.9000000,
339 0.8333333,
340 0.8000000,
341 0.7500000,
342 0.7000000,
343 0.6666667,
344 0.6000000,
345 0.5000000,
346 0.4000000,
347 0.3333333,
348 0.3000000,
349 0.2500000,
350 0.2000000,
351 0.1666667,
352 0.1428571,
353 0.1250000,
354 0.1111111,
355 0.1000000,
356 0.0500000,
357 );
358
359 // Put the None option at the top.
360 self::$fractionoptions = array(
361 '0.0' => get_string('none'),
362 '1.0' => '100%',
363 );
364 self::$fractionoptionsfull = array(
365 '0.0' => get_string('none'),
366 '1.0' => '100%',
367 );
368
369 // The the positive grades in descending order.
370 foreach ($rawfractions as $fraction) {
371 $percentage = (100 * $fraction) . '%';
372 self::$fractionoptions["$fraction"] = $percentage;
373 self::$fractionoptionsfull["$fraction"] = $percentage;
374 }
375
376 // The the negative grades in descending order.
377 foreach (array_reverse($rawfractions) as $fraction) {
378 self::$fractionoptionsfull['' . (-$fraction)] = (-100 * $fraction) . '%';
379 }
380
381 self::$fractionoptionsfull['-1.0'] = '-100%';
382 }
383
384 /**
385 * @return array string => string The standard set of grade options (fractions)
386 * to use when editing questions, in the range 0 to 1 inclusive. Array keys
387 * are string becuase: a) we want grades to exactly 7 d.p., and b. you can't
388 * have float array keys in PHP.
389 * Initialised by {@link ensure_grade_options_initialised()}.
390 */
391 public static function fraction_options() {
392 self::ensure_fraction_options_initialised();
393 return self::$fractionoptions;
394 }
395
396 /** @return array string => string The full standard set of (fractions) -1 to 1 inclusive. */
397 public static function fraction_options_full() {
398 self::ensure_fraction_options_initialised();
399 return self::$fractionoptionsfull;
400 }
2ec325c2
TH
401
402 /**
403 * Perform scheduled maintenance tasks relating to the question bank.
404 */
405 public static function cron() {
406 global $CFG;
407
408 // Delete any old question preview that got left in the database.
409 require_once($CFG->dirroot . '/question/previewlib.php');
410 question_preview_cron();
411 }
d1b7e03d
TH
412}
413
f7970e3c
TH
414
415/**
416 * Class for loading questions according to various criteria.
417 *
418 * @copyright 2009 The Open University
419 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
420 */
d1b7e03d
TH
421class question_finder {
422 /**
423 * Get the ids of all the questions in a list of categoryies.
2daffca5 424 * @param array $categoryids either a categoryid, or a comma-separated list
d1b7e03d 425 * category ids, or an array of them.
2daffca5
TH
426 * @param string $extraconditions extra conditions to AND with the rest of
427 * the where clause. Must use named parameters.
428 * @param array $extraparams any parameters used by $extraconditions.
d1b7e03d
TH
429 * @return array questionid => questionid.
430 */
9c197f44
TH
431 public function get_questions_from_categories($categoryids, $extraconditions,
432 $extraparams = array()) {
f9b0500f
TH
433 global $DB;
434
a2ac2349 435 list($qcsql, $qcparams) = $DB->get_in_or_equal($categoryids, SQL_PARAMS_NAMED, 'qc');
d1b7e03d
TH
436
437 if ($extraconditions) {
438 $extraconditions = ' AND (' . $extraconditions . ')';
439 }
2daffca5
TH
440
441 return $DB->get_records_select_menu('question',
442 "category $qcsql
d1b7e03d
TH
443 AND parent = 0
444 AND hidden = 0
2daffca5 445 $extraconditions", $qcparams + $extraparams, '', 'id,id AS id2');
d1b7e03d
TH
446 }
447}