Search moodle.org's
Developer Documentation

See Release Notes
Long Term Support Release

  • Bug fixes for general core bugs in 4.1.x will end 13 November 2023 (12 months).
  • Bug fixes for security issues in 4.1.x will end 10 November 2025 (36 months).
  • PHP version: minimum PHP 7.4.0 Note: minimum PHP version has increased since Moodle 4.0. PHP 8.0.x is supported too.

Differences Between: [Versions 310 and 401] [Versions 311 and 401] [Versions 39 and 401] [Versions 400 and 401] [Versions 401 and 403]

   1  <?php
   2  // This file is part of Moodle - http://moodle.org/
   3  //
   4  // Moodle is free software: you can redistribute it and/or modify
   5  // it under the terms of the GNU General Public License as published by
   6  // the Free Software Foundation, either version 3 of the License, or
   7  // (at your option) any later version.
   8  //
   9  // Moodle is distributed in the hope that it will be useful,
  10  // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  12  // GNU General Public License for more details.
  13  //
  14  // You should have received a copy of the GNU General Public License
  15  // along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
  16  
  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   *
  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
  28   */
  29  
  30  
  31  defined('MOODLE_INTERNAL') || die();
  32  
  33  require_once (__DIR__ . '/../type/questiontypebase.php');
  34  
  35  
  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   *
  41   * @copyright  2009 The Open University
  42   * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  43   */
  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;
  47  
  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      /** @var boolean nasty hack to allow unit tests to call {@link load_question()}. */
  55      private static $testmode = false;
  56      private static $testdata = array();
  57  
  58      private static $questionconfig = null;
  59  
  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()}.
  66       */
  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;
  70  
  71      /**
  72       * @param string $qtypename a question type name, e.g. 'multichoice'.
  73       * @return bool whether that question type is installed in this Moodle.
  74       */
  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');
  78      }
  79  
  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.
  86       */
  87      public static function get_qtype($qtypename, $mustexist = true) {
  88          global $CFG;
  89          if (isset(self::$questiontypes[$qtypename])) {
  90              return self::$questiontypes[$qtypename];
  91          }
  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');
  98              }
  99          }
 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}.");
 104          }
 105          self::$questiontypes[$qtypename] = new $class();
 106          return self::$questiontypes[$qtypename];
 107      }
 108  
 109      /**
 110       * Load the question configuration data from config_plugins.
 111       * @return object get_config('question') with caching.
 112       */
 113      public static function get_config() {
 114          if (is_null(self::$questionconfig)) {
 115              self::$questionconfig = get_config('question');
 116          }
 117          return self::$questionconfig;
 118      }
 119  
 120      /**
 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.
 123       */
 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() != '';
 129      }
 130  
 131      /**
 132       * @param string $qtypename the internal name of a question type. For example multichoice.
 133       * @return bool whether this question type exists.
 134       */
 135      public static function qtype_exists($qtypename) {
 136          return array_key_exists($qtypename, core_component::get_plugin_list('qtype'));
 137      }
 138  
 139      /**
 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.
 142       */
 143      public static function get_qtype_name($qtypename) {
 144          return self::get_qtype($qtypename)->local_name();
 145      }
 146  
 147      /**
 148       * @return array all the installed question types.
 149       */
 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.
 158              }
 159          }
 160          return $qtypes;
 161      }
 162  
 163      /**
 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.
 168       */
 169      public static function sort_qtype_array($qtypes, $config = null) {
 170          if (is_null($config)) {
 171              $config = self::get_config();
 172          }
 173  
 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;
 182              }
 183          }
 184  
 185          ksort($sortorder);
 186          core_collator::asort($otherqtypes);
 187  
 188          $sortedqtypes = array();
 189          foreach ($sortorder as $name) {
 190              $sortedqtypes[$name] = $qtypes[$name];
 191          }
 192          foreach ($otherqtypes as $name => $notused) {
 193              $sortedqtypes[$name] = $qtypes[$name];
 194          }
 195          return $sortedqtypes;
 196      }
 197  
 198      /**
 199       * @return array all the question types that users are allowed to create,
 200       *      sorted into the preferred order set on the admin screen.
 201       */
 202      public static function get_creatable_qtypes() {
 203          $config = self::get_config();
 204          $allqtypes = self::get_all_qtypes();
 205  
 206          $qtypenames = array();
 207          foreach ($allqtypes as $name => $qtype) {
 208              if (self::qtype_enabled($name)) {
 209                  $qtypenames[$name] = $qtype->local_name();
 210              }
 211          }
 212  
 213          $qtypenames = self::sort_qtype_array($qtypenames);
 214  
 215          $creatableqtypes = array();
 216          foreach ($qtypenames as $name => $notused) {
 217              $creatableqtypes[$name] = $allqtypes[$name];
 218          }
 219          return $creatableqtypes;
 220      }
 221  
 222      /**
 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'.
 227       */
 228      public static function load_question_definition_classes($qtypename) {
 229          global $CFG;
 230          if (isset(self::$loadedqdefs[$qtypename])) {
 231              return;
 232          }
 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);
 236          }
 237          include_once($file);
 238          self::$loadedqdefs[$qtypename] = 1;
 239      }
 240  
 241      /**
 242       * This method needs to be called whenever a question is edited.
 243       */
 244      public static function notify_question_edited($questionid) {
 245          question_finder::get_instance()->uncache_question($questionid);
 246      }
 247  
 248      /**
 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.
 253       */
 254      public static function load_question_data($questionid) {
 255          return question_finder::get_instance()->load_question_data($questionid);
 256      }
 257  
 258      /**
 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.
 265       */
 266      public static function load_question($questionid, $allowshuffle = true) {
 267  
 268          if (self::$testmode) {
 269              // Evil, test code in production, but no way round it.
 270              return self::return_test_question_data($questionid);
 271          }
 272  
 273          $questiondata = self::load_question_data($questionid);
 274  
 275          if (!$allowshuffle) {
 276              $questiondata->options->shuffleanswers = false;
 277          }
 278          return self::make_question($questiondata);
 279      }
 280  
 281      /**
 282       * Convert the question information loaded with {@link get_question_options()}
 283       * to a question_definintion object.
 284       * @param object $questiondata raw data loaded from the database.
 285       * @return question_definition loaded from the database.
 286       */
 287      public static function make_question($questiondata) {
 288          return self::get_qtype($questiondata->qtype, false)->make_question($questiondata, false);
 289      }
 290  
 291      /**
 292       * Get all the versions of a particular question.
 293       *
 294       * @param int $questionid id of the question
 295       * @return array The array keys are version number, and the values are objects with three int fields
 296       * version (same as array key), versionid and questionid.
 297       */
 298      public static function get_all_versions_of_question(int $questionid): array {
 299          global $DB;
 300          $sql = "SELECT qv.id AS versionid, qv.version, qv.questionid
 301                    FROM {question_versions} qv
 302                   WHERE qv.questionbankentryid = (SELECT DISTINCT qbe.id
 303                                                     FROM {question_bank_entries} qbe
 304                                                     JOIN {question_versions} qv ON qbe.id = qv.questionbankentryid
 305                                                     JOIN {question} q ON qv.questionid = q.id
 306                                                    WHERE q.id = ?)
 307                ORDER BY qv.version DESC";
 308  
 309          return $DB->get_records_sql($sql, [$questionid]);
 310      }
 311  
 312      /**
 313       * Get all the versions of questions.
 314       *
 315       * @param array $questionids Array of question ids.
 316       * @return array two dimensional array question_bank_entries.id => version number => question.id.
 317       *      Versions in descending order.
 318       */
 319      public static function get_all_versions_of_questions(array $questionids): array {
 320          global $DB;
 321  
 322          [$listquestionid, $params] = $DB->get_in_or_equal($questionids, SQL_PARAMS_NAMED);
 323          $sql = "SELECT qv.questionid, qv.version, qv.questionbankentryid
 324                    FROM {question_versions} qv
 325                    JOIN {question_versions} qv2 ON qv.questionbankentryid = qv2.questionbankentryid
 326                   WHERE qv2.questionid $listquestionid
 327                ORDER BY qv.questionbankentryid, qv.version DESC";
 328          $result = [];
 329          $rows = $DB->get_recordset_sql($sql, $params);
 330          foreach ($rows as $row) {
 331              $result[$row->questionbankentryid][$row->version] = $row->questionid;
 332          }
 333  
 334          return $result;
 335      }
 336  
 337      /**
 338       * @return question_finder a question finder.
 339       */
 340      public static function get_finder() {
 341          return question_finder::get_instance();
 342      }
 343  
 344      /**
 345       * Only to be called from unit tests. Allows {@link load_test_data()} to be used.
 346       */
 347      public static function start_unit_test() {
 348          self::$testmode = true;
 349      }
 350  
 351      /**
 352       * Only to be called from unit tests. Allows {@link load_test_data()} to be used.
 353       */
 354      public static function end_unit_test() {
 355          self::$testmode = false;
 356          self::$testdata = array();
 357      }
 358  
 359      private static function return_test_question_data($questionid) {
 360          if (!isset(self::$testdata[$questionid])) {
 361              throw new coding_exception('question_bank::return_test_data(' . $questionid .
 362                      ') called, but no matching question has been loaded by load_test_data.');
 363          }
 364          return self::$testdata[$questionid];
 365      }
 366  
 367      /**
 368       * To be used for unit testing only. Will throw an exception if
 369       * {@link start_unit_test()} has not been called first.
 370       * @param object $questiondata a question data object to put in the test data store.
 371       */
 372      public static function load_test_question_data(question_definition $question) {
 373          if (!self::$testmode) {
 374              throw new coding_exception('question_bank::load_test_data called when ' .
 375                      'not in test mode.');
 376          }
 377          self::$testdata[$question->id] = $question;
 378      }
 379  
 380      protected static function ensure_fraction_options_initialised() {
 381          if (!is_null(self::$fractionoptions)) {
 382              return;
 383          }
 384  
 385          // define basic array of grades. This list comprises all fractions of the form:
 386          // a. p/q for q <= 6, 0 <= p <= q
 387          // b. p/10 for 0 <= p <= 10
 388          // c. 1/q for 1 <= q <= 10
 389          // d. 1/20
 390          $rawfractions = array(
 391              0.9000000,
 392              0.8333333,
 393              0.8000000,
 394              0.7500000,
 395              0.7000000,
 396              0.6666667,
 397              0.6000000,
 398              0.5000000,
 399              0.4000000,
 400              0.3333333,
 401              0.3000000,
 402              0.2500000,
 403              0.2000000,
 404              0.1666667,
 405              0.1428571,
 406              0.1250000,
 407              0.1111111,
 408              0.1000000,
 409              0.0500000,
 410          );
 411  
 412          // Put the None option at the top.
 413          self::$fractionoptions = array(
 414              '0.0' => get_string('none'),
 415              '1.0' => '100%',
 416          );
 417          self::$fractionoptionsfull = array(
 418              '0.0' => get_string('none'),
 419              '1.0' => '100%',
 420          );
 421  
 422          // The the positive grades in descending order.
 423          foreach ($rawfractions as $fraction) {
 424              $percentage = format_float(100 * $fraction, 5, true, true) . '%';
 425              self::$fractionoptions["{$fraction}"] = $percentage;
 426              self::$fractionoptionsfull["{$fraction}"] = $percentage;
 427          }
 428  
 429          // The the negative grades in descending order.
 430          foreach (array_reverse($rawfractions) as $fraction) {
 431              self::$fractionoptionsfull['' . (-$fraction)] =
 432                      format_float(-100 * $fraction, 5, true, true) . '%';
 433          }
 434  
 435          self::$fractionoptionsfull['-1.0'] = '-100%';
 436      }
 437  
 438      /**
 439       * @return array string => string The standard set of grade options (fractions)
 440       * to use when editing questions, in the range 0 to 1 inclusive. Array keys
 441       * are string becuase: a) we want grades to exactly 7 d.p., and b. you can't
 442       * have float array keys in PHP.
 443       * Initialised by {@link ensure_grade_options_initialised()}.
 444       */
 445      public static function fraction_options() {
 446          self::ensure_fraction_options_initialised();
 447          return self::$fractionoptions;
 448      }
 449  
 450      /** @return array string => string The full standard set of (fractions) -1 to 1 inclusive. */
 451      public static function fraction_options_full() {
 452          self::ensure_fraction_options_initialised();
 453          return self::$fractionoptionsfull;
 454      }
 455  
 456      /**
 457       * Return a list of the different question types present in the given categories.
 458       *
 459       * @param  array $categories a list of category ids
 460       * @return array the list of question types in the categories
 461       * @since  Moodle 3.1
 462       */
 463      public static function get_all_question_types_in_categories($categories) {
 464          global $DB;
 465  
 466          list($categorysql, $params) = $DB->get_in_or_equal($categories);
 467          $sql = "SELECT DISTINCT q.qtype
 468                             FROM {question} q
 469                             JOIN {question_versions} qv ON qv.questionid = q.id
 470                             JOIN {question_bank_entries} qbe ON qbe.id = qv.questionbankentryid
 471                            WHERE qbe.questioncategoryid $categorysql";
 472  
 473          $qtypes = $DB->get_fieldset_sql($sql, $params);
 474          return $qtypes;
 475      }
 476  }
 477  
 478  
 479  /**
 480   * Class for loading questions according to various criteria.
 481   *
 482   * @copyright  2009 The Open University
 483   * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 484   */
 485  class question_finder implements cache_data_source {
 486      /** @var question_finder the singleton instance of this class. */
 487      protected static $questionfinder = null;
 488  
 489      /**
 490       * @return question_finder a question finder.
 491       */
 492      public static function get_instance() {
 493          if (is_null(self::$questionfinder)) {
 494              self::$questionfinder = new question_finder();
 495          }
 496          return self::$questionfinder;
 497      }
 498  
 499      /* See cache_data_source::get_instance_for_cache. */
 500      public static function get_instance_for_cache(cache_definition $definition) {
 501          return self::get_instance();
 502      }
 503  
 504      /**
 505       * @return cache_application the question definition cache we are using.
 506       */
 507      protected function get_data_cache() {
 508          // Do not double cache here because it may break cache resetting.
 509          return cache::make('core', 'questiondata');
 510      }
 511  
 512      /**
 513       * This method needs to be called whenever a question is edited.
 514       */
 515      public function uncache_question($questionid) {
 516          $this->get_data_cache()->delete($questionid);
 517      }
 518  
 519      /**
 520       * Load a question definition data from the database. The data will be
 521       * returned as a plain stdClass object.
 522       * @param int $questionid the id of the question to load.
 523       * @return object question definition loaded from the database.
 524       */
 525      public function load_question_data($questionid) {
 526          return $this->get_data_cache()->get($questionid);
 527      }
 528  
 529      /**
 530       * Get the ids of all the questions in a list of categories.
 531       * @param array $categoryids either a category id, or a comma-separated list
 532       *      of category ids, or an array of them.
 533       * @param string $extraconditions extra conditions to AND with the rest of
 534       *      the where clause. Must use named parameters.
 535       * @param array $extraparams any parameters used by $extraconditions.
 536       * @return array questionid => questionid.
 537       */
 538      public function get_questions_from_categories($categoryids, $extraconditions,
 539              $extraparams = array()) {
 540          global $DB;
 541  
 542          list($qcsql, $qcparams) = $DB->get_in_or_equal($categoryids, SQL_PARAMS_NAMED, 'qc');
 543  
 544          if ($extraconditions) {
 545              $extraconditions = ' AND (' . $extraconditions . ')';
 546          }
 547          $qcparams['readystatus'] = \core_question\local\bank\question_version_status::QUESTION_STATUS_READY;
 548          $qcparams['readystatusqv'] = \core_question\local\bank\question_version_status::QUESTION_STATUS_READY;
 549          $sql = "SELECT q.id, q.id AS id2
 550                    FROM {question} q
 551                    JOIN {question_versions} qv ON qv.questionid = q.id
 552                    JOIN {question_bank_entries} qbe ON qbe.id = qv.questionbankentryid
 553                   WHERE qbe.questioncategoryid {$qcsql}
 554                         AND q.parent = 0
 555                         AND qv.status = :readystatus
 556                         AND qv.version = (SELECT MAX(v.version)
 557                                            FROM {question_versions} v
 558                                            JOIN {question_bank_entries} be
 559                                              ON be.id = v.questionbankentryid
 560                                           WHERE be.id = qbe.id
 561                                             AND v.status = :readystatusqv)
 562                         {$extraconditions}";
 563  
 564          return $DB->get_records_sql_menu($sql, $qcparams + $extraparams);
 565      }
 566  
 567      /**
 568       * Get the ids of all the questions in a list of categories, with the number
 569       * of times they have already been used in a given set of usages.
 570       *
 571       * The result array is returned in order of increasing (count previous uses).
 572       *
 573       * @param array $categoryids an array question_category ids.
 574       * @param qubaid_condition $qubaids which question_usages to count previous uses from.
 575       * @param string $extraconditions extra conditions to AND with the rest of
 576       *      the where clause. Must use named parameters.
 577       * @param array $extraparams any parameters used by $extraconditions.
 578       * @return array questionid => count of number of previous uses.
 579       */
 580      public function get_questions_from_categories_with_usage_counts($categoryids,
 581              qubaid_condition $qubaids, $extraconditions = '', $extraparams = array()) {
 582          return $this->get_questions_from_categories_and_tags_with_usage_counts(
 583                  $categoryids, $qubaids, $extraconditions, $extraparams);
 584      }
 585  
 586      /**
 587       * Get the ids of all the questions in a list of categories that have ALL the provided tags,
 588       * with the number of times they have already been used in a given set of usages.
 589       *
 590       * The result array is returned in order of increasing (count previous uses).
 591       *
 592       * @param array $categoryids an array of question_category ids.
 593       * @param qubaid_condition $qubaids which question_usages to count previous uses from.
 594       * @param string $extraconditions extra conditions to AND with the rest of
 595       *      the where clause. Must use named parameters.
 596       * @param array $extraparams any parameters used by $extraconditions.
 597       * @param array $tagids an array of tag ids
 598       * @return array questionid => count of number of previous uses.
 599       */
 600      public function get_questions_from_categories_and_tags_with_usage_counts($categoryids,
 601              qubaid_condition $qubaids, $extraconditions = '', $extraparams = array(), $tagids = array()) {
 602          global $DB;
 603  
 604          list($qcsql, $qcparams) = $DB->get_in_or_equal($categoryids, SQL_PARAMS_NAMED, 'qc');
 605  
 606          $readystatus = \core_question\local\bank\question_version_status::QUESTION_STATUS_READY;
 607          $select = "q.id, (SELECT COUNT(1)
 608                              FROM " . $qubaids->from_question_attempts('qa') . "
 609                             WHERE qa.questionid = q.id AND " . $qubaids->where() . "
 610                           ) AS previous_attempts";
 611          $from   = "{question} q";
 612          $join   = "JOIN {question_versions} qv ON qv.questionid = q.id
 613                     JOIN {question_bank_entries} qbe ON qbe.id = qv.questionbankentryid";
 614          $from = $from . " " . $join;
 615          $where  = "qbe.questioncategoryid {$qcsql}
 616                 AND q.parent = 0
 617                 AND qv.status = '$readystatus'
 618                 AND qv.version = (SELECT MAX(v.version)
 619                                    FROM {question_versions} v
 620                                    JOIN {question_bank_entries} be
 621                                      ON be.id = v.questionbankentryid
 622                                   WHERE be.id = qbe.id)";
 623          $params = $qcparams;
 624  
 625          if (!empty($tagids)) {
 626              // We treat each additional tag as an AND condition rather than
 627              // an OR condition.
 628              //
 629              // For example, if the user filters by the tags "foo" and "bar" then
 630              // we reduce the question list to questions that are tagged with both
 631              // "foo" AND "bar". Any question that does not have ALL of the specified
 632              // tags will be omitted.
 633              list($tagsql, $tagparams) = $DB->get_in_or_equal($tagids, SQL_PARAMS_NAMED, 'ti');
 634              $tagparams['tagcount'] = count($tagids);
 635              $tagparams['questionitemtype'] = 'question';
 636              $tagparams['questioncomponent'] = 'core_question';
 637              $where .= " AND q.id IN (SELECT ti.itemid
 638                                         FROM {tag_instance} ti
 639                                        WHERE ti.itemtype = :questionitemtype
 640                                              AND ti.component = :questioncomponent
 641                                              AND ti.tagid {$tagsql}
 642                                     GROUP BY ti.itemid
 643                                       HAVING COUNT(itemid) = :tagcount)";
 644              $params += $tagparams;
 645          }
 646  
 647          if ($extraconditions) {
 648              $extraconditions = ' AND (' . $extraconditions . ')';
 649          }
 650  
 651          return $DB->get_records_sql_menu("SELECT $select
 652                                                  FROM $from
 653                                                 WHERE $where $extraconditions
 654                                              ORDER BY previous_attempts",
 655                  $qubaids->from_where_params() + $params + $extraparams);
 656      }
 657  
 658      /* See cache_data_source::load_for_cache. */
 659      public function load_for_cache($questionid) {
 660          global $DB;
 661  
 662          $sql = 'SELECT q.id, qc.id as category, q.parent, q.name, q.questiontext, q.questiontextformat,
 663                         q.generalfeedback, q.generalfeedbackformat, q.defaultmark, q.penalty, q.qtype,
 664                         q.length, q.stamp, q.timecreated, q.timemodified,
 665                         q.createdby, q.modifiedby, qbe.idnumber,
 666                         qc.contextid,
 667                         qv.status,
 668                         qv.id as versionid,
 669                         qv.version,
 670                         qv.questionbankentryid
 671                    FROM {question} q
 672                    JOIN {question_versions} qv ON qv.questionid = q.id
 673                    JOIN {question_bank_entries} qbe ON qbe.id = qv.questionbankentryid
 674                    JOIN {question_categories} qc ON qc.id = qbe.questioncategoryid
 675                   WHERE q.id = :id';
 676  
 677          $questiondata = $DB->get_record_sql($sql, ['id' => $questionid], MUST_EXIST);
 678          get_question_options($questiondata);
 679          return $questiondata;
 680      }
 681  
 682      /* See cache_data_source::load_many_for_cache. */
 683      public function load_many_for_cache(array $questionids) {
 684          global $DB;
 685          list($idcondition, $params) = $DB->get_in_or_equal($questionids);
 686          $sql = 'SELECT q.id, qc.id as category, q.parent, q.name, q.questiontext, q.questiontextformat,
 687                         q.generalfeedback, q.generalfeedbackformat, q.defaultmark, q.penalty, q.qtype,
 688                         q.length, q.stamp, q.timecreated, q.timemodified,
 689                         q.createdby, q.modifiedby, qbe.idnumber,
 690                         qc.contextid,
 691                         qv.status,
 692                         qv.id as versionid,
 693                         qv.version,
 694                         qv.questionbankentryid
 695                    FROM {question} q
 696                    JOIN {question_versions} qv ON qv.questionid = q.id
 697                    JOIN {question_bank_entries} qbe ON qbe.id = qv.questionbankentryid
 698                    JOIN {question_categories} qc ON qc.id = qbe.questioncategoryid
 699                   WHERE q.id ';
 700  
 701          $questiondata = $DB->get_records_sql($sql . $idcondition, $params);
 702  
 703          foreach ($questionids as $id) {
 704              if (!array_key_exists($id, $questiondata)) {
 705                  throw new dml_missing_record_exception('question', '', ['id' => $id]);
 706              }
 707              get_question_options($questiondata[$id]);
 708          }
 709          return $questiondata;
 710      }
 711  }