MDL-52035 enrol_lti: added fix for oracle
[moodle.git] / question / engine / bank.php
blob99e2de529f5bedbcbb16d32a9aa5b6bfb24c9257
1 <?php
2 // This file is part of Moodle - http://moodle.org/
3 //
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
8 //
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
17 /**
18 * More object oriented wrappers around parts of the Moodle question bank.
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.
24 * @package moodlecore
25 * @subpackage questionbank
26 * @copyright 2009 The Open University
27 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
31 defined('MOODLE_INTERNAL') || die();
33 require_once(dirname(__FILE__) . '/../type/questiontypebase.php');
36 /**
37 * This static class provides access to the other question bank.
39 * It provides functions for managing question types and question definitions.
41 * @copyright 2009 The Open University
42 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
44 abstract class question_bank {
45 // TODO: This limit can be deleted if someday we move all TEXTS to BIG ones. MDL-19603
46 const MAX_SUMMARY_LENGTH = 32000;
48 /** @var array question type name => question_type subclass. */
49 private static $questiontypes = array();
51 /** @var array question type name => 1. Records which question definitions have been loaded. */
52 private static $loadedqdefs = array();
54 /** @var boolean nasty hack to allow unit tests to call {@link load_question()}. */
55 private static $testmode = false;
56 private static $testdata = array();
58 private static $questionconfig = null;
60 /**
61 * @var array string => string The standard set of grade options (fractions)
62 * to use when editing questions, in the range 0 to 1 inclusive. Array keys
63 * are string becuase: a) we want grades to exactly 7 d.p., and b. you can't
64 * have float array keys in PHP.
65 * Initialised by {@link ensure_grade_options_initialised()}.
67 private static $fractionoptions = null;
68 /** @var array string => string The full standard set of (fractions) -1 to 1 inclusive. */
69 private static $fractionoptionsfull = null;
71 /**
72 * @param string $qtypename a question type name, e.g. 'multichoice'.
73 * @return bool whether that question type is installed in this Moodle.
75 public static function is_qtype_installed($qtypename) {
76 $plugindir = core_component::get_plugin_directory('qtype', $qtypename);
77 return $plugindir && is_readable($plugindir . '/questiontype.php');
80 /**
81 * Get the question type class for a particular question type.
82 * @param string $qtypename the question type name. For example 'multichoice' or 'shortanswer'.
83 * @param bool $mustexist if false, the missing question type is returned when
84 * the requested question type is not installed.
85 * @return question_type the corresponding question type class.
87 public static function get_qtype($qtypename, $mustexist = true) {
88 global $CFG;
89 if (isset(self::$questiontypes[$qtypename])) {
90 return self::$questiontypes[$qtypename];
92 $file = core_component::get_plugin_directory('qtype', $qtypename) . '/questiontype.php';
93 if (!is_readable($file)) {
94 if ($mustexist || $qtypename == 'missingtype') {
95 throw new coding_exception('Unknown question type ' . $qtypename);
96 } else {
97 return self::get_qtype('missingtype');
100 include_once($file);
101 $class = 'qtype_' . $qtypename;
102 if (!class_exists($class)) {
103 throw new coding_exception("Class {$class} must be defined in {$file}.");
105 self::$questiontypes[$qtypename] = new $class();
106 return self::$questiontypes[$qtypename];
110 * Load the question configuration data from config_plugins.
111 * @return object get_config('question') with caching.
113 public static function get_config() {
114 if (is_null(self::$questionconfig)) {
115 self::$questionconfig = get_config('question');
117 return self::$questionconfig;
121 * @param string $qtypename the internal name of a question type. For example multichoice.
122 * @return bool whether users are allowed to create questions of this type.
124 public static function qtype_enabled($qtypename) {
125 $config = self::get_config();
126 $enabledvar = $qtypename . '_disabled';
127 return self::qtype_exists($qtypename) && empty($config->$enabledvar) &&
128 self::get_qtype($qtypename)->menu_name() != '';
132 * @param string $qtypename the internal name of a question type. For example multichoice.
133 * @return bool whether this question type exists.
135 public static function qtype_exists($qtypename) {
136 return array_key_exists($qtypename, core_component::get_plugin_list('qtype'));
140 * @param $qtypename the internal name of a question type, for example multichoice.
141 * @return string the human_readable name of this question type, from the language pack.
143 public static function get_qtype_name($qtypename) {
144 return self::get_qtype($qtypename)->local_name();
148 * @return array all the installed question types.
150 public static function get_all_qtypes() {
151 $qtypes = array();
152 foreach (core_component::get_plugin_list('qtype') as $plugin => $notused) {
153 try {
154 $qtypes[$plugin] = self::get_qtype($plugin);
155 } catch (coding_exception $e) {
156 // Catching coding_exceptions here means that incompatible
157 // question types do not cause the rest of Moodle to break.
160 return $qtypes;
164 * Sort an array of question types according to the order the admin set up,
165 * and then alphabetically for the rest.
166 * @param array qtype->name() => qtype->local_name().
167 * @return array sorted array.
169 public static function sort_qtype_array($qtypes, $config = null) {
170 if (is_null($config)) {
171 $config = self::get_config();
174 $sortorder = array();
175 $otherqtypes = array();
176 foreach ($qtypes as $name => $localname) {
177 $sortvar = $name . '_sortorder';
178 if (isset($config->$sortvar)) {
179 $sortorder[$config->$sortvar] = $name;
180 } else {
181 $otherqtypes[$name] = $localname;
185 ksort($sortorder);
186 core_collator::asort($otherqtypes);
188 $sortedqtypes = array();
189 foreach ($sortorder as $name) {
190 $sortedqtypes[$name] = $qtypes[$name];
192 foreach ($otherqtypes as $name => $notused) {
193 $sortedqtypes[$name] = $qtypes[$name];
195 return $sortedqtypes;
199 * @return array all the question types that users are allowed to create,
200 * sorted into the preferred order set on the admin screen.
202 public static function get_creatable_qtypes() {
203 $config = self::get_config();
204 $allqtypes = self::get_all_qtypes();
206 $qtypenames = array();
207 foreach ($allqtypes as $name => $qtype) {
208 if (self::qtype_enabled($name)) {
209 $qtypenames[$name] = $qtype->local_name();
213 $qtypenames = self::sort_qtype_array($qtypenames);
215 $creatableqtypes = array();
216 foreach ($qtypenames as $name => $notused) {
217 $creatableqtypes[$name] = $allqtypes[$name];
219 return $creatableqtypes;
223 * Load the question definition class(es) belonging to a question type. That is,
224 * include_once('/question/type/' . $qtypename . '/question.php'), with a bit
225 * of checking.
226 * @param string $qtypename the question type name. For example 'multichoice' or 'shortanswer'.
228 public static function load_question_definition_classes($qtypename) {
229 global $CFG;
230 if (isset(self::$loadedqdefs[$qtypename])) {
231 return;
233 $file = $CFG->dirroot . '/question/type/' . $qtypename . '/question.php';
234 if (!is_readable($file)) {
235 throw new coding_exception('Unknown question type (no definition) ' . $qtypename);
237 include_once($file);
238 self::$loadedqdefs[$qtypename] = 1;
242 * This method needs to be called whenever a question is edited.
244 public static function notify_question_edited($questionid) {
245 question_finder::get_instance()->uncache_question($questionid);
249 * Load a question definition data from the database. The data will be
250 * returned as a plain stdClass object.
251 * @param int $questionid the id of the question to load.
252 * @return object question definition loaded from the database.
254 public static function load_question_data($questionid) {
255 return question_finder::get_instance()->load_question_data($questionid);
259 * Load a question definition from the database. The object returned
260 * will actually be of an appropriate {@link question_definition} subclass.
261 * @param int $questionid the id of the question to load.
262 * @param bool $allowshuffle if false, then any shuffle option on the selected
263 * quetsion is disabled.
264 * @return question_definition loaded from the database.
266 public static function load_question($questionid, $allowshuffle = true) {
267 global $DB;
269 if (self::$testmode) {
270 // Evil, test code in production, but now way round it.
271 return self::return_test_question_data($questionid);
274 $questiondata = self::load_question_data($questionid);
276 if (!$allowshuffle) {
277 $questiondata->options->shuffleanswers = false;
279 return self::make_question($questiondata);
283 * Convert the question information loaded with {@link get_question_options()}
284 * to a question_definintion object.
285 * @param object $questiondata raw data loaded from the database.
286 * @return question_definition loaded from the database.
288 public static function make_question($questiondata) {
289 return self::get_qtype($questiondata->qtype, false)->make_question($questiondata, false);
293 * @return question_finder a question finder.
295 public static function get_finder() {
296 return question_finder::get_instance();
297 if (is_null(self::$questionfinder)) {
298 self::$questionfinder = new question_finder();
300 return self::$questionfinder;
304 * Only to be called from unit tests. Allows {@link load_test_data()} to be used.
306 public static function start_unit_test() {
307 self::$testmode = true;
311 * Only to be called from unit tests. Allows {@link load_test_data()} to be used.
313 public static function end_unit_test() {
314 self::$testmode = false;
315 self::$testdata = array();
318 private static function return_test_question_data($questionid) {
319 if (!isset(self::$testdata[$questionid])) {
320 throw new coding_exception('question_bank::return_test_data(' . $questionid .
321 ') called, but no matching question has been loaded by load_test_data.');
323 return self::$testdata[$questionid];
327 * To be used for unit testing only. Will throw an exception if
328 * {@link start_unit_test()} has not been called first.
329 * @param object $questiondata a question data object to put in the test data store.
331 public static function load_test_question_data(question_definition $question) {
332 if (!self::$testmode) {
333 throw new coding_exception('question_bank::load_test_data called when ' .
334 'not in test mode.');
336 self::$testdata[$question->id] = $question;
339 protected static function ensure_fraction_options_initialised() {
340 if (!is_null(self::$fractionoptions)) {
341 return;
344 // define basic array of grades. This list comprises all fractions of the form:
345 // a. p/q for q <= 6, 0 <= p <= q
346 // b. p/10 for 0 <= p <= 10
347 // c. 1/q for 1 <= q <= 10
348 // d. 1/20
349 $rawfractions = array(
350 0.9000000,
351 0.8333333,
352 0.8000000,
353 0.7500000,
354 0.7000000,
355 0.6666667,
356 0.6000000,
357 0.5000000,
358 0.4000000,
359 0.3333333,
360 0.3000000,
361 0.2500000,
362 0.2000000,
363 0.1666667,
364 0.1428571,
365 0.1250000,
366 0.1111111,
367 0.1000000,
368 0.0500000,
371 // Put the None option at the top.
372 self::$fractionoptions = array(
373 '0.0' => get_string('none'),
374 '1.0' => '100%',
376 self::$fractionoptionsfull = array(
377 '0.0' => get_string('none'),
378 '1.0' => '100%',
381 // The the positive grades in descending order.
382 foreach ($rawfractions as $fraction) {
383 $percentage = format_float(100 * $fraction, 5, true, true) . '%';
384 self::$fractionoptions["{$fraction}"] = $percentage;
385 self::$fractionoptionsfull["{$fraction}"] = $percentage;
388 // The the negative grades in descending order.
389 foreach (array_reverse($rawfractions) as $fraction) {
390 self::$fractionoptionsfull['' . (-$fraction)] =
391 format_float(-100 * $fraction, 5, true, true) . '%';
394 self::$fractionoptionsfull['-1.0'] = '-100%';
398 * @return array string => string The standard set of grade options (fractions)
399 * to use when editing questions, in the range 0 to 1 inclusive. Array keys
400 * are string becuase: a) we want grades to exactly 7 d.p., and b. you can't
401 * have float array keys in PHP.
402 * Initialised by {@link ensure_grade_options_initialised()}.
404 public static function fraction_options() {
405 self::ensure_fraction_options_initialised();
406 return self::$fractionoptions;
409 /** @return array string => string The full standard set of (fractions) -1 to 1 inclusive. */
410 public static function fraction_options_full() {
411 self::ensure_fraction_options_initialised();
412 return self::$fractionoptionsfull;
416 * Perform scheduled maintenance tasks relating to the question bank.
418 public static function cron() {
419 global $CFG;
421 // Delete any old question preview that got left in the database.
422 require_once($CFG->dirroot . '/question/previewlib.php');
423 question_preview_cron();
425 // Clear older calculated stats from cache.
426 require_once($CFG->dirroot . '/question/engine/statisticslib.php');
427 question_usage_statistics_cron();
431 * Return a list of the different question types present in the given categories.
433 * @param array $categories a list of category ids
434 * @return array the list of question types in the categories
435 * @since Moodle 3.1
437 public static function get_all_question_types_in_categories($categories) {
438 global $DB;
440 list($categorysql, $params) = $DB->get_in_or_equal($categories);
441 $sql = "SELECT DISTINCT q.qtype
442 FROM {question} q
443 WHERE q.category $categorysql";
445 $qtypes = $DB->get_fieldset_sql($sql, $params);
446 return $qtypes;
452 * Class for loading questions according to various criteria.
454 * @copyright 2009 The Open University
455 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
457 class question_finder implements cache_data_source {
458 /** @var question_finder the singleton instance of this class. */
459 protected static $questionfinder = null;
462 * @return question_finder a question finder.
464 public static function get_instance() {
465 if (is_null(self::$questionfinder)) {
466 self::$questionfinder = new question_finder();
468 return self::$questionfinder;
471 /* See cache_data_source::get_instance_for_cache. */
472 public static function get_instance_for_cache(cache_definition $definition) {
473 return self::get_instance();
477 * @return get the question definition cache we are using.
479 protected function get_data_cache() {
480 // Do not double cache here because it may break cache resetting.
481 return cache::make('core', 'questiondata');
485 * This method needs to be called whenever a question is edited.
487 public function uncache_question($questionid) {
488 $this->get_data_cache()->delete($questionid);
492 * Load a question definition data from the database. The data will be
493 * returned as a plain stdClass object.
494 * @param int $questionid the id of the question to load.
495 * @return object question definition loaded from the database.
497 public function load_question_data($questionid) {
498 return $this->get_data_cache()->get($questionid);
502 * Get the ids of all the questions in a list of categories.
503 * @param array $categoryids either a categoryid, or a comma-separated list
504 * category ids, or an array of them.
505 * @param string $extraconditions extra conditions to AND with the rest of
506 * the where clause. Must use named parameters.
507 * @param array $extraparams any parameters used by $extraconditions.
508 * @return array questionid => questionid.
510 public function get_questions_from_categories($categoryids, $extraconditions,
511 $extraparams = array()) {
512 global $DB;
514 list($qcsql, $qcparams) = $DB->get_in_or_equal($categoryids, SQL_PARAMS_NAMED, 'qc');
516 if ($extraconditions) {
517 $extraconditions = ' AND (' . $extraconditions . ')';
520 return $DB->get_records_select_menu('question',
521 "category {$qcsql}
522 AND parent = 0
523 AND hidden = 0
524 {$extraconditions}", $qcparams + $extraparams, '', 'id,id AS id2');
528 * Get the ids of all the questions in a list of categories, with the number
529 * of times they have already been used in a given set of usages.
531 * The result array is returned in order of increasing (count previous uses).
533 * @param array $categoryids an array question_category ids.
534 * @param qubaid_condition $qubaids which question_usages to count previous uses from.
535 * @param string $extraconditions extra conditions to AND with the rest of
536 * the where clause. Must use named parameters.
537 * @param array $extraparams any parameters used by $extraconditions.
538 * @return array questionid => count of number of previous uses.
540 public function get_questions_from_categories_with_usage_counts($categoryids,
541 qubaid_condition $qubaids, $extraconditions = '', $extraparams = array()) {
542 global $DB;
544 list($qcsql, $qcparams) = $DB->get_in_or_equal($categoryids, SQL_PARAMS_NAMED, 'qc');
546 if ($extraconditions) {
547 $extraconditions = ' AND (' . $extraconditions . ')';
550 return $DB->get_records_sql_menu("
551 SELECT q.id, (SELECT COUNT(1)
552 FROM " . $qubaids->from_question_attempts('qa') . "
553 WHERE qa.questionid = q.id AND " . $qubaids->where() . "
554 ) AS previous_attempts
556 FROM {question} q
558 WHERE q.category {$qcsql}
559 AND q.parent = 0
560 AND q.hidden = 0
561 {$extraconditions}
563 ORDER BY previous_attempts
564 ", $qubaids->from_where_params() + $qcparams + $extraparams);
567 /* See cache_data_source::load_for_cache. */
568 public function load_for_cache($questionid) {
569 global $DB;
570 $questiondata = $DB->get_record_sql('
571 SELECT q.*, qc.contextid
572 FROM {question} q
573 JOIN {question_categories} qc ON q.category = qc.id
574 WHERE q.id = :id', array('id' => $questionid), MUST_EXIST);
575 get_question_options($questiondata);
576 return $questiondata;
579 /* See cache_data_source::load_many_for_cache. */
580 public function load_many_for_cache(array $questionids) {
581 global $DB;
582 list($idcondition, $params) = $DB->get_in_or_equal($questionids);
583 $questiondata = $DB->get_records_sql('
584 SELECT q.*, qc.contextid
585 FROM {question} q
586 JOIN {question_categories} qc ON q.category = qc.id
587 WHERE q.id ' . $idcondition, $params);
589 foreach ($questionids as $id) {
590 if (!array_key_exists($id, $questionids)) {
591 throw new dml_missing_record_exception('question', '', array('id' => $id));
593 get_question_options($questiondata[$id]);
595 return $questiondata;