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 402] [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   * Code for handling and processing questions.
  19   *
  20   * This is code that is module independent, i.e., can be used by any module that
  21   * uses questions, like quiz, lesson, etc.
  22   * This script also loads the questiontype classes.
  23   * Code for handling the editing of questions is in question/editlib.php
  24   *
  25   * @package    core
  26   * @subpackage questionbank
  27   * @copyright  1999 onwards Martin Dougiamas and others {@link http://moodle.com}
  28   * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  29   */
  30  
  31  use core_question\local\bank\question_version_status;
  32  use core_question\question_reference_manager;
  33  
  34  defined('MOODLE_INTERNAL') || die();
  35  
  36  require_once($CFG->dirroot . '/question/engine/lib.php');
  37  require_once($CFG->dirroot . '/question/type/questiontypebase.php');
  38  
  39  
  40  
  41  // CONSTANTS.
  42  
  43  /**
  44   * Constant determines the number of answer boxes supplied in the editing
  45   * form for multiple choice and similar question types.
  46   */
  47  define("QUESTION_NUMANS", 10);
  48  
  49  /**
  50   * Constant determines the number of answer boxes supplied in the editing
  51   * form for multiple choice and similar question types to start with, with
  52   * the option of adding QUESTION_NUMANS_ADD more answers.
  53   */
  54  define("QUESTION_NUMANS_START", 3);
  55  
  56  /**
  57   * Constant determines the number of answer boxes to add in the editing
  58   * form for multiple choice and similar question types when the user presses
  59   * 'add form fields button'.
  60   */
  61  define("QUESTION_NUMANS_ADD", 3);
  62  
  63  /**
  64   * Move one question type in a list of question types. If you try to move one element
  65   * off of the end, nothing will change.
  66   *
  67   * @param array $sortedqtypes An array $qtype => anything.
  68   * @param string $tomove one of the keys from $sortedqtypes
  69   * @param integer $direction +1 or -1
  70   * @return array an array $index => $qtype, with $index from 0 to n in order, and
  71   *      the $qtypes in the same order as $sortedqtypes, except that $tomove will
  72   *      have been moved one place.
  73   */
  74  function question_reorder_qtypes($sortedqtypes, $tomove, $direction): array {
  75      $neworder = array_keys($sortedqtypes);
  76      // Find the element to move.
  77      $key = array_search($tomove, $neworder);
  78      if ($key === false) {
  79          return $neworder;
  80      }
  81      // Work out the other index.
  82      $otherkey = $key + $direction;
  83      if (!isset($neworder[$otherkey])) {
  84          return $neworder;
  85      }
  86      // Do the swap.
  87      $swap = $neworder[$otherkey];
  88      $neworder[$otherkey] = $neworder[$key];
  89      $neworder[$key] = $swap;
  90      return $neworder;
  91  }
  92  
  93  /**
  94   * Save a new question type order to the config_plugins table.
  95   *
  96   * @param array $neworder An arra $index => $qtype. Indices should start at 0 and be in order.
  97   * @param object $config get_config('question'), if you happen to have it around, to save one DB query.
  98   */
  99  function question_save_qtype_order($neworder, $config = null): void {
 100      if (is_null($config)) {
 101          $config = get_config('question');
 102      }
 103  
 104      foreach ($neworder as $index => $qtype) {
 105          $sortvar = $qtype . '_sortorder';
 106          if (!isset($config->$sortvar) || $config->$sortvar != $index + 1) {
 107              set_config($sortvar, $index + 1, 'question');
 108          }
 109      }
 110  }
 111  
 112  // FUNCTIONS.
 113  
 114  /**
 115   * Check if the question is used.
 116   *
 117   * @param array $questionids of question ids.
 118   * @return boolean whether any of these questions are being used by any part of Moodle.
 119   */
 120  function questions_in_use($questionids): bool {
 121  
 122      // Are they used by the core question system?
 123      if (question_engine::questions_in_use($questionids)) {
 124          return true;
 125      }
 126  
 127      if (question_reference_manager::questions_with_references($questionids)) {
 128          return true;
 129      }
 130  
 131      // Check if any plugins are using these questions.
 132      $callbacksbytype = get_plugins_with_function('questions_in_use');
 133      foreach ($callbacksbytype as $callbacks) {
 134          foreach ($callbacks as $function) {
 135              if ($function($questionids)) {
 136                  return true;
 137              }
 138          }
 139      }
 140  
 141      // Finally check legacy callback.
 142      $legacycallbacks = get_plugin_list_with_function('mod', 'question_list_instances');
 143      foreach ($legacycallbacks as $plugin => $function) {
 144          debugging($plugin . ' implements deprecated method ' . $function .
 145                  '. ' . $plugin . '_questions_in_use should be implemented instead.', DEBUG_DEVELOPER);
 146  
 147          if (isset($callbacksbytype['mod'][substr($plugin, 4)])) {
 148              continue; // Already done.
 149          }
 150  
 151          foreach ($questionids as $questionid) {
 152              if (!empty($function($questionid))) {
 153                  return true;
 154              }
 155          }
 156      }
 157  
 158      return false;
 159  }
 160  
 161  /**
 162   * Determine whether there are any questions belonging to this context, that is whether any of its
 163   * question categories contain any questions. This will return true even if all the questions are
 164   * hidden.
 165   *
 166   * @param mixed $context either a context object, or a context id.
 167   * @return boolean whether any of the question categories beloning to this context have
 168   *         any questions in them.
 169   */
 170  function question_context_has_any_questions($context): bool {
 171      global $DB;
 172      if (is_object($context)) {
 173          $contextid = $context->id;
 174      } else if (is_numeric($context)) {
 175          $contextid = $context;
 176      } else {
 177          throw new moodle_exception('invalidcontextinhasanyquestions', 'question');
 178      }
 179      $sql = 'SELECT qbe.*
 180                FROM {question_bank_entries} qbe
 181                JOIN {question_categories} qc ON qc.id = qbe.questioncategoryid
 182               WHERE qc.contextid = ?';
 183      return $DB->record_exists_sql($sql, [$contextid]);
 184  }
 185  
 186  /**
 187   * Check whether a given grade is one of a list of allowed options. If not,
 188   * depending on $matchgrades, either return the nearest match, or return false
 189   * to signal an error.
 190   *
 191   * @param array $gradeoptionsfull list of valid options
 192   * @param int $grade grade to be tested
 193   * @param string $matchgrades 'error' or 'nearest'
 194   * @return false|int|string either 'fixed' value or false if error.
 195   */
 196  function match_grade_options($gradeoptionsfull, $grade, $matchgrades = 'error') {
 197  
 198      if ($matchgrades == 'error') {
 199          // ...(Almost) exact match, or an error.
 200          foreach ($gradeoptionsfull as $value => $option) {
 201              // Slightly fuzzy test, never check floats for equality.
 202              if (abs($grade - $value) < 0.00001) {
 203                  return $value; // Be sure the return the proper value.
 204              }
 205          }
 206          // Didn't find a match so that's an error.
 207          return false;
 208  
 209      } else if ($matchgrades == 'nearest') {
 210          // Work out nearest value.
 211          $best = false;
 212          $bestmismatch = 2;
 213          foreach ($gradeoptionsfull as $value => $option) {
 214              $newmismatch = abs($grade - $value);
 215              if ($newmismatch < $bestmismatch) {
 216                  $best = $value;
 217                  $bestmismatch = $newmismatch;
 218              }
 219          }
 220          return $best;
 221  
 222      } else {
 223          // Unknow option passed.
 224          throw new coding_exception('Unknown $matchgrades ' . $matchgrades .
 225                  ' passed to match_grade_options');
 226      }
 227  }
 228  
 229  /**
 230   * Category is about to be deleted,
 231   * 1/ All questions are deleted for this question category.
 232   * 2/ Any questions that can't be deleted are moved to a new category
 233   * NOTE: this function is called from lib/db/upgrade.php
 234   *
 235   * @param object|core_course_category $category course category object
 236   */
 237  function question_category_delete_safe($category): void {
 238      global $DB;
 239      $criteria = ['questioncategoryid' => $category->id];
 240      $context = context::instance_by_id($category->contextid, IGNORE_MISSING);
 241      $rescue = null; // See the code around the call to question_save_from_deletion.
 242  
 243      // Deal with any questions in the category.
 244      if ($questionentries = $DB->get_records('question_bank_entries', $criteria, '', 'id')) {
 245  
 246          foreach ($questionentries as $questionentry) {
 247              $questionids = $DB->get_records('question_versions',
 248                                                  ['questionbankentryid' => $questionentry->id], '', 'questionid');
 249  
 250              // Try to delete each question.
 251              foreach ($questionids as $questionid) {
 252                  question_delete_question($questionid->questionid, $category->contextid);
 253              }
 254          }
 255  
 256          // Check to see if there were any questions that were kept because
 257          // they are still in use somehow, even though quizzes in courses
 258          // in this category will already have been deleted. This could
 259          // happen, for example, if questions are added to a course,
 260          // and then that course is moved to another category (MDL-14802).
 261          $questionids = [];
 262          foreach ($questionentries as $questionentry) {
 263              $versions = $DB->get_records('question_versions', ['questionbankentryid' => $questionentry->id], '', 'questionid');
 264              foreach ($versions as $key => $version) {
 265                  $questionids[$key] = $version;
 266              }
 267          }
 268          if (!empty($questionids)) {
 269              $parentcontextid = SYSCONTEXTID;
 270              $name = get_string('unknown', 'question');
 271              if ($context !== false) {
 272                  $name = $context->get_context_name();
 273                  $parentcontext = $context->get_parent_context();
 274                  if ($parentcontext) {
 275                      $parentcontextid = $parentcontext->id;
 276                  }
 277              }
 278              question_save_from_deletion(array_keys($questionids), $parentcontextid, $name, $rescue);
 279          }
 280      }
 281  
 282      // Now delete the category.
 283      $DB->delete_records('question_categories', ['id' => $category->id]);
 284  }
 285  
 286  /**
 287   * Tests whether any question in a category is used by any part of Moodle.
 288   *
 289   * @param integer $categoryid a question category id.
 290   * @param boolean $recursive whether to check child categories too.
 291   * @return boolean whether any question in this category is in use.
 292   */
 293  function question_category_in_use($categoryid, $recursive = false): bool {
 294      global $DB;
 295  
 296      // Look at each question in the category.
 297      $questionids = question_bank::get_finder()->get_questions_from_categories([$categoryid], null);
 298      if ($questionids) {
 299          if (questions_in_use(array_keys($questionids))) {
 300              return true;
 301          }
 302      }
 303      if (!$recursive) {
 304          return false;
 305      }
 306  
 307      // Look under child categories recursively.
 308      if ($children = $DB->get_records('question_categories',
 309              ['parent' => $categoryid], '', 'id, 1')) {
 310          foreach ($children as $child) {
 311              if (question_category_in_use($child->id, $recursive)) {
 312                  return true;
 313              }
 314          }
 315      }
 316  
 317      return false;
 318  }
 319  
 320  /**
 321   * Check if there is more versions left for the entry.
 322   * If not delete the entry.
 323   *
 324   * @param int $entryid
 325   */
 326  function delete_question_bank_entry($entryid): void {
 327      global $DB;
 328      if (!$DB->record_exists('question_versions', ['questionbankentryid' => $entryid])) {
 329          $DB->delete_records('question_bank_entries', ['id' => $entryid]);
 330      }
 331  }
 332  
 333  /**
 334   * Deletes question and all associated data from the database
 335   *
 336   * It will not delete a question if it is used somewhere, instead it will just delete the reference.
 337   *
 338   * @param int $questionid The id of the question being deleted
 339   */
 340  function question_delete_question($questionid): void {
 341      global $DB;
 342  
 343      $question = $DB->get_record('question', ['id' => $questionid]);
 344      if (!$question) {
 345          // In some situations, for example if this was a child of a
 346          // Cloze question that was previously deleted, the question may already
 347          // have gone. In this case, just do nothing.
 348          return;
 349      }
 350  
 351      $sql = 'SELECT qv.id as versionid,
 352                     qv.version,
 353                     qbe.id as entryid,
 354                     qc.id as categoryid,
 355                     ctx.id as contextid
 356                FROM {question} q
 357                LEFT JOIN {question_versions} qv ON qv.questionid = q.id
 358                LEFT JOIN {question_bank_entries} qbe ON qbe.id = qv.questionbankentryid
 359                LEFT JOIN {question_categories} qc ON qc.id = qbe.questioncategoryid
 360                LEFT JOIN {context} ctx ON ctx.id = qc.contextid
 361               WHERE q.id = ?';
 362      $questiondata = $DB->get_record_sql($sql, [$question->id]);
 363  
 364      $questionstocheck = [$question->id];
 365  
 366      if ($question->parent) {
 367          $questionstocheck[] = $question->parent;
 368      }
 369  
 370      // Do not delete a question if it is used by an activity module. Just mark the version hidden.
 371      if (questions_in_use($questionstocheck)) {
 372          $DB->set_field('question_versions', 'status',
 373                  question_version_status::QUESTION_STATUS_HIDDEN, ['questionid' => $questionid]);
 374          return;
 375      }
 376  
 377      // This sometimes happens in old sites with bad data.
 378      if (!$questiondata->contextid) {
 379          debugging('Deleting question ' . $question->id . ' which is no longer linked to a context. ' .
 380              'Assuming system context to avoid errors, but this may mean that some data like files, ' .
 381              'tags, are not cleaned up.');
 382          $questiondata->contextid = context_system::instance()->id;
 383          $questiondata->categoryid = 0;
 384      }
 385  
 386      // Delete previews of the question.
 387      $dm = new question_engine_data_mapper();
 388      $dm->delete_previews($question->id);
 389  
 390      // Delete questiontype-specific data.
 391      question_bank::get_qtype($question->qtype, false)->delete_question($question->id, $questiondata->contextid);
 392  
 393      // Delete all tag instances.
 394      core_tag_tag::remove_all_item_tags('core_question', 'question', $question->id);
 395  
 396      // Delete the custom filed data for the question.
 397      $customfieldhandler = qbank_customfields\customfield\question_handler::create();
 398      $customfieldhandler->delete_instance($question->id);
 399  
 400      // Now recursively delete all child questions
 401      if ($children = $DB->get_records('question',
 402              array('parent' => $questionid), '', 'id, qtype')) {
 403          foreach ($children as $child) {
 404              if ($child->id != $questionid) {
 405                  question_delete_question($child->id);
 406              }
 407          }
 408      }
 409  
 410      // Delete question comments.
 411      $DB->delete_records('comments', ['itemid' => $questionid, 'component' => 'qbank_comment',
 412                                              'commentarea' => 'question']);
 413      // Finally delete the question record itself.
 414      $DB->delete_records('question', ['id' => $question->id]);
 415      $DB->delete_records('question_versions', ['id' => $questiondata->versionid]);
 416      $DB->delete_records('question_references',
 417          [
 418              'version' => $questiondata->version,
 419              'questionbankentryid' => $questiondata->entryid,
 420          ]);
 421      delete_question_bank_entry($questiondata->entryid);
 422      question_bank::notify_question_edited($question->id);
 423  
 424      // Log the deletion of this question.
 425      $question->category = $questiondata->categoryid;
 426      $question->contextid = $questiondata->contextid;
 427      $event = \core\event\question_deleted::create_from_question_instance($question);
 428      $event->add_record_snapshot('question', $question);
 429      $event->trigger();
 430  }
 431  
 432  /**
 433   * All question categories and their questions are deleted for this context id.
 434   *
 435   * @param int $contextid The contextid to delete question categories from
 436   * @return array only returns an empty array for backwards compatibility.
 437   */
 438  function question_delete_context($contextid): array {
 439      global $DB;
 440  
 441      $fields = 'id, parent, name, contextid';
 442      if ($categories = $DB->get_records('question_categories', ['contextid' => $contextid], 'parent', $fields)) {
 443          // Sort categories following their tree (parent-child) relationships this will make the feedback more readable.
 444          $categories = sort_categories_by_tree($categories);
 445          foreach ($categories as $category) {
 446              question_category_delete_safe($category);
 447          }
 448      }
 449      return [];
 450  }
 451  
 452  /**
 453   * All question categories and their questions are deleted for this course.
 454   *
 455   * @param stdClass $course an object representing the activity
 456   * @param bool $notused this argument is not used any more. Kept for backwards compatibility.
 457   * @return bool always true.
 458   */
 459  function question_delete_course($course, $notused = false): bool {
 460      $coursecontext = context_course::instance($course->id);
 461      question_delete_context($coursecontext->id);
 462      return true;
 463  }
 464  
 465  /**
 466   * Category is about to be deleted,
 467   * 1/ All question categories and their questions are deleted for this course category.
 468   * 2/ All questions are moved to new category
 469   *
 470   * @param stdClass|core_course_category $category course category object
 471   * @param stdClass|core_course_category $newcategory empty means everything deleted, otherwise id of
 472   *      category where content moved
 473   * @param bool $notused this argument is no longer used. Kept for backwards compatibility.
 474   * @return boolean
 475   */
 476  function question_delete_course_category($category, $newcategory, $notused=false): bool {
 477      global $DB;
 478  
 479      $context = context_coursecat::instance($category->id);
 480      if (empty($newcategory)) {
 481          question_delete_context($context->id);
 482  
 483      } else {
 484          // Move question categories to the new context.
 485          if (!$newcontext = context_coursecat::instance($newcategory->id)) {
 486              return false;
 487          }
 488  
 489          // Only move question categories if there is any question category at all!
 490          if ($topcategory = question_get_top_category($context->id)) {
 491              $newtopcategory = question_get_top_category($newcontext->id, true);
 492  
 493              question_move_category_to_context($topcategory->id, $context->id, $newcontext->id);
 494              $DB->set_field('question_categories', 'parent', $newtopcategory->id, ['parent' => $topcategory->id]);
 495              // Now delete the top category.
 496              $DB->delete_records('question_categories', ['id' => $topcategory->id]);
 497          }
 498      }
 499  
 500      return true;
 501  }
 502  
 503  /**
 504   * Creates a new category to save the questions in use.
 505   *
 506   * @param array $questionids of question ids
 507   * @param object $newcontextid the context to create the saved category in.
 508   * @param string $oldplace a textual description of the think being deleted,
 509   *      e.g. from get_context_name
 510   * @param object $newcategory
 511   * @return mixed false on
 512   */
 513  function question_save_from_deletion($questionids, $newcontextid, $oldplace, $newcategory = null) {
 514      global $DB;
 515  
 516      // Make a category in the parent context to move the questions to.
 517      if (is_null($newcategory)) {
 518          $newcategory = new stdClass();
 519          $newcategory->parent = question_get_top_category($newcontextid, true)->id;
 520          $newcategory->contextid = $newcontextid;
 521          // Max length of column name in question_categories is 255.
 522          $newcategory->name = shorten_text(get_string('questionsrescuedfrom', 'question', $oldplace), 255);
 523          $newcategory->info = get_string('questionsrescuedfrominfo', 'question', $oldplace);
 524          $newcategory->sortorder = 999;
 525          $newcategory->stamp = make_unique_id_code();
 526          $newcategory->id = $DB->insert_record('question_categories', $newcategory);
 527      }
 528  
 529      // Move any remaining questions to the 'saved' category.
 530      if (!question_move_questions_to_category($questionids, $newcategory->id)) {
 531          return false;
 532      }
 533      return $newcategory;
 534  }
 535  
 536  /**
 537   * All question categories and their questions are deleted for this activity.
 538   *
 539   * @param object $cm the course module object representing the activity
 540   * @param bool $notused the argument is not used any more. Kept for backwards compatibility.
 541   * @return boolean
 542   */
 543  function question_delete_activity($cm, $notused = false): bool {
 544      $modcontext = context_module::instance($cm->id);
 545      question_delete_context($modcontext->id);
 546      return true;
 547  }
 548  
 549  /**
 550   * This function will handle moving all tag instances to a new context for a
 551   * given list of questions.
 552   *
 553   * Questions can be tagged in up to two contexts:
 554   * 1.) The context the question exists in.
 555   * 2.) The course context (if the question context is a higher context.
 556   *     E.g. course category context or system context.
 557   *
 558   * This means a question that exists in a higher context (e.g. course cat or
 559   * system context) may have multiple groups of tags in any number of child
 560   * course contexts.
 561   *
 562   * Questions in the course category context can be move "down" a context level
 563   * into one of their child course contexts or activity contexts which affects the
 564   * availability of that question in other courses / activities.
 565   *
 566   * In this case it makes the questions no longer available in the other course or
 567   * activity contexts so we need to make sure that the tag instances in those other
 568   * contexts are removed.
 569   *
 570   * @param stdClass[] $questions The list of question being moved (must include
 571   *                              the id and contextid)
 572   * @param context $newcontext The Moodle context the questions are being moved to
 573   */
 574  function question_move_question_tags_to_new_context(array $questions, context $newcontext): void {
 575      // If the questions are moving to a new course/activity context then we need to
 576      // find any existing tag instances from any unavailable course contexts and
 577      // delete them because they will no longer be applicable (we don't support
 578      // tagging questions across courses).
 579      $instancestodelete = [];
 580      $instancesfornewcontext = [];
 581      $newcontextparentids = $newcontext->get_parent_context_ids();
 582      $questionids = array_map(function($question) {
 583          return $question->id;
 584      }, $questions);
 585      $questionstagobjects = core_tag_tag::get_items_tags('core_question', 'question', $questionids);
 586  
 587      foreach ($questions as $question) {
 588          $tagobjects = $questionstagobjects[$question->id] ?? [];
 589  
 590          foreach ($tagobjects as $tagobject) {
 591              $tagid = $tagobject->taginstanceid;
 592              $tagcontextid = $tagobject->taginstancecontextid;
 593              $istaginnewcontext = $tagcontextid == $newcontext->id;
 594              $istaginquestioncontext = $tagcontextid == $question->contextid;
 595  
 596              if ($istaginnewcontext) {
 597                  // This tag instance is already in the correct context so we can
 598                  // ignore it.
 599                  continue;
 600              }
 601  
 602              if ($istaginquestioncontext) {
 603                  // This tag instance is in the question context so it needs to be
 604                  // updated.
 605                  $instancesfornewcontext[] = $tagid;
 606                  continue;
 607              }
 608  
 609              // These tag instances are in neither the new context nor the
 610              // question context so we need to determine what to do based on
 611              // the context they are in and the new question context.
 612              $tagcontext = context::instance_by_id($tagcontextid);
 613              $tagcoursecontext = $tagcontext->get_course_context(false);
 614              // The tag is in a course context if get_course_context() returns
 615              // itself.
 616              $istaginstancecontextcourse = !empty($tagcoursecontext)
 617                  && $tagcontext->id == $tagcoursecontext->id;
 618  
 619              if ($istaginstancecontextcourse) {
 620                  // If the tag instance is in a course context we need to add some
 621                  // special handling.
 622                  $tagcontextparentids = $tagcontext->get_parent_context_ids();
 623                  $isnewcontextaparent = in_array($newcontext->id, $tagcontextparentids);
 624                  $isnewcontextachild = in_array($tagcontext->id, $newcontextparentids);
 625  
 626                  if ($isnewcontextaparent) {
 627                      // If the tag instance is a course context tag and the new
 628                      // context is still a parent context to the tag context then
 629                      // we can leave this tag where it is.
 630                      continue;
 631                  } else if ($isnewcontextachild) {
 632                      // If the new context is a child context (e.g. activity) of this
 633                      // tag instance then we should move all of this tag instance
 634                      // down into the activity context along with the question.
 635                      $instancesfornewcontext[] = $tagid;
 636                  } else {
 637                      // If the tag is in a course context that is no longer a parent
 638                      // or child of the new context then this tag instance should be
 639                      // removed.
 640                      $instancestodelete[] = $tagid;
 641                  }
 642              } else {
 643                  // This is a catch all for any tag instances not in the question
 644                  // context or a course context. These tag instances should be
 645                  // updated to the new context id. This will clean up old invalid
 646                  // data.
 647                  $instancesfornewcontext[] = $tagid;
 648              }
 649          }
 650      }
 651  
 652      if (!empty($instancestodelete)) {
 653          // Delete any course context tags that may no longer be valid.
 654          core_tag_tag::delete_instances_by_id($instancestodelete);
 655      }
 656  
 657      if (!empty($instancesfornewcontext)) {
 658          // Update the tag instances to the new context id.
 659          core_tag_tag::change_instances_context($instancesfornewcontext, $newcontext);
 660      }
 661  }
 662  
 663  /**
 664   * Check if an idnumber exist in the category.
 665   *
 666   * @param int $questionidnumber
 667   * @param int $categoryid
 668   * @param int $limitfrom
 669   * @param int $limitnum
 670   * @return array
 671   */
 672  function idnumber_exist_in_question_category($questionidnumber, $categoryid, $limitfrom = 0, $limitnum = 1): array {
 673      global $DB;
 674      $response  = false;
 675      $record = [];
 676      // Check if the idnumber exist in the category.
 677      $sql = 'SELECT qbe.idnumber
 678                FROM {question_bank_entries} qbe
 679               WHERE qbe.idnumber LIKE ?
 680                 AND qbe.questioncategoryid = ?
 681            ORDER BY qbe.idnumber DESC';
 682      $questionrecord = $DB->record_exists_sql($sql, [$questionidnumber, $categoryid]);
 683      if ((string) $questionidnumber !== '' && $questionrecord) {
 684          $record = $DB->get_records_sql($sql, [$questionidnumber . '_%', $categoryid], 0, 1);
 685          $response  = true;
 686      }
 687  
 688      return [$response, $record];
 689  }
 690  
 691  /**
 692   * This function should be considered private to the question bank, it is called from
 693   * question/editlib.php question/contextmoveq.php and a few similar places to to the
 694   * work of actually moving questions and associated data. However, callers of this
 695   * function also have to do other work, which is why you should not call this method
 696   * directly from outside the questionbank.
 697   *
 698   * @param array $questionids of question ids.
 699   * @param integer $newcategoryid the id of the category to move to.
 700   * @return bool
 701   */
 702  function question_move_questions_to_category($questionids, $newcategoryid): bool {
 703      global $DB;
 704  
 705      $newcategorydata = $DB->get_record('question_categories', ['id' => $newcategoryid]);
 706      if (!$newcategorydata) {
 707          return false;
 708      }
 709      list($questionidcondition, $params) = $DB->get_in_or_equal($questionids);
 710  
 711      $sql = "SELECT qv.id as versionid,
 712                     qbe.id as entryid,
 713                     qc.id as category,
 714                     qc.contextid as contextid,
 715                     q.id,
 716                     q.qtype,
 717                     qbe.idnumber
 718                FROM {question} q
 719                JOIN {question_versions} qv ON qv.questionid = q.id
 720                JOIN {question_bank_entries} qbe ON qbe.id = qv.questionbankentryid
 721                JOIN {question_categories} qc ON qc.id = qbe.questioncategoryid
 722               WHERE q.id $questionidcondition
 723                     OR (q.parent <> 0 AND q.parent $questionidcondition)";
 724  
 725      // Also, we need to move children questions.
 726      $params = array_merge($params, $params);
 727      $questions = $DB->get_records_sql($sql, $params);
 728      foreach ($questions as $question) {
 729          if ($newcategorydata->contextid != $question->contextid) {
 730              question_bank::get_qtype($question->qtype)->move_files(
 731                      $question->id, $question->contextid, $newcategorydata->contextid);
 732          }
 733          // Check whether there could be a clash of idnumbers in the new category.
 734          list($idnumberclash, $rec) = idnumber_exist_in_question_category($question->idnumber, $newcategoryid);
 735          if ($idnumberclash) {
 736              $unique = 1;
 737              if (count($rec)) {
 738                  $rec = reset($rec);
 739                  $idnumber = $rec->idnumber;
 740                  if (strpos($idnumber, '_') !== false) {
 741                      $unique = substr($idnumber, strpos($idnumber, '_') + 1) + 1;
 742                  }
 743              }
 744              // For the move process, add a numerical increment to the idnumber. This means that if a question is
 745              // mistakenly moved then the idnumber will not be completely lost.
 746              $qbankentry = new stdClass();
 747              $qbankentry->id = $question->entryid;
 748              $qbankentry->idnumber = $question->idnumber . '_' . $unique;
 749              $DB->update_record('question_bank_entries', $qbankentry);
 750          }
 751  
 752          // Update the entry to the new category id.
 753          $entry = new stdClass();
 754          $entry->id = $question->entryid;
 755          $entry->questioncategoryid = $newcategorydata->id;
 756          $DB->update_record('question_bank_entries', $entry);
 757  
 758          // Log this question move.
 759          $event = \core\event\question_moved::create_from_question_instance($question, context::instance_by_id($question->contextid),
 760                  ['oldcategoryid' => $question->category, 'newcategoryid' => $newcategorydata->id]);
 761          $event->trigger();
 762      }
 763  
 764      $newcontext = context::instance_by_id($newcategorydata->contextid);
 765      question_move_question_tags_to_new_context($questions, $newcontext);
 766  
 767      // TODO Deal with datasets.
 768  
 769      // Purge these questions from the cache.
 770      foreach ($questions as $question) {
 771          question_bank::notify_question_edited($question->id);
 772      }
 773  
 774      return true;
 775  }
 776  
 777  /**
 778   * Update the questioncontextid field for all question_set_references records given a new context id
 779   *
 780   * @param int $oldcategoryid Old category to be moved.
 781   * @param int $newcatgoryid New category that will receive the questions.
 782   * @param int $oldcontextid Old context to be moved.
 783   * @param int $newcontextid New context that will receive the questions.
 784   * @param bool $delete If the action is delete.
 785   * @throws dml_exception
 786   */
 787  function move_question_set_references(int $oldcategoryid, int $newcatgoryid,
 788                                        int $oldcontextid, int $newcontextid, bool $delete = false): void {
 789      global $DB;
 790  
 791      if ($delete || $oldcontextid !== $newcontextid) {
 792          $setreferences = $DB->get_recordset('question_set_references', ['questionscontextid' => $oldcontextid]);
 793          foreach ($setreferences as $setreference) {
 794              $filter = json_decode($setreference->filtercondition);
 795              if (isset($filter->questioncategoryid)) {
 796                  if ((int)$filter->questioncategoryid === $oldcategoryid) {
 797                      $setreference->questionscontextid = $newcontextid;
 798                      if ($oldcategoryid !== $newcatgoryid) {
 799                          $filter->questioncategoryid = $newcatgoryid;
 800                          $setreference->filtercondition = json_encode($filter);
 801                      }
 802                      $DB->update_record('question_set_references', $setreference);
 803                  }
 804              }
 805          }
 806          $setreferences->close();
 807      }
 808  }
 809  
 810  /**
 811   * This function helps move a question cateogry to a new context by moving all
 812   * the files belonging to all the questions to the new context.
 813   * Also moves subcategories.
 814   * @param integer $categoryid the id of the category being moved.
 815   * @param integer $oldcontextid the old context id.
 816   * @param integer $newcontextid the new context id.
 817   */
 818  function question_move_category_to_context($categoryid, $oldcontextid, $newcontextid): void {
 819      global $DB;
 820  
 821      $questions = [];
 822      $sql = "SELECT q.id, q.qtype
 823                FROM {question} q
 824                JOIN {question_versions} qv ON qv.questionid = q.id
 825                JOIN {question_bank_entries} qbe ON qbe.id = qv.questionbankentryid
 826               WHERE qbe.questioncategoryid = ?";
 827  
 828      $questionids = $DB->get_records_sql_menu($sql, [$categoryid]);
 829      foreach ($questionids as $questionid => $qtype) {
 830          question_bank::get_qtype($qtype)->move_files($questionid, $oldcontextid, $newcontextid);
 831          // Purge this question from the cache.
 832          question_bank::notify_question_edited($questionid);
 833  
 834          $questions[] = (object) [
 835              'id' => $questionid,
 836              'contextid' => $oldcontextid
 837          ];
 838      }
 839  
 840      $newcontext = context::instance_by_id($newcontextid);
 841      question_move_question_tags_to_new_context($questions, $newcontext);
 842  
 843      $subcatids = $DB->get_records_menu('question_categories', ['parent' => $categoryid], '', 'id,1');
 844      foreach ($subcatids as $subcatid => $notused) {
 845          $DB->set_field('question_categories', 'contextid', $newcontextid, ['id' => $subcatid]);
 846          question_move_category_to_context($subcatid, $oldcontextid, $newcontextid);
 847      }
 848  }
 849  
 850  /**
 851   * Given a list of ids, load the basic information about a set of questions from
 852   * the questions table. The $join and $extrafields arguments can be used together
 853   * to pull in extra data. See, for example, the usage in mod/quiz/attemptlib.php, and
 854   * read the code below to see how the SQL is assembled. Throws exceptions on error.
 855   *
 856   * @param array $questionids array of question ids to load. If null, then all
 857   * questions matched by $join will be loaded.
 858   * @param string $extrafields extra SQL code to be added to the query.
 859   * @param string $join extra SQL code to be added to the query.
 860   * @param array $extraparams values for any placeholders in $join.
 861   * You must use named placeholders.
 862   * @param string $orderby what to order the results by. Optional, default is unspecified order.
 863   *
 864   * @return array partially complete question objects. You need to call get_question_options
 865   * on them before they can be properly used.
 866   */
 867  function question_preload_questions($questionids = null, $extrafields = '', $join = '', $extraparams = [], $orderby = ''): array {
 868      global $DB;
 869  
 870      if ($questionids === null) {
 871          $extracondition = '';
 872          $params = [];
 873      } else {
 874          if (empty($questionids)) {
 875              return [];
 876          }
 877  
 878          list($questionidcondition, $params) = $DB->get_in_or_equal($questionids, SQL_PARAMS_NAMED, 'qid0000');
 879          $extracondition = 'WHERE q.id ' . $questionidcondition;
 880      }
 881  
 882      if ($join) {
 883          $join = 'JOIN ' . $join;
 884      }
 885  
 886      if ($extrafields) {
 887          $extrafields = ', ' . $extrafields;
 888      }
 889  
 890      if ($orderby) {
 891          $orderby = 'ORDER BY ' . $orderby;
 892      }
 893  
 894      $sql = "SELECT q.*,
 895                     qc.id as category,
 896                     qv.status,
 897                     qv.id as versionid,
 898                     qv.version,
 899                     qv.questionbankentryid,
 900                     qc.contextid as contextid
 901                     {$extrafields}
 902                FROM {question} q
 903                JOIN {question_versions} qv
 904                  ON qv.questionid = q.id
 905                JOIN {question_bank_entries} qbe
 906                  ON qbe.id = qv.questionbankentryid
 907                JOIN {question_categories} qc
 908                  ON qc.id = qbe.questioncategoryid
 909                {$join}
 910                {$extracondition}
 911                {$orderby}";
 912  
 913      // Load the questions.
 914      $questions = $DB->get_records_sql($sql, $extraparams + $params);
 915      foreach ($questions as $question) {
 916          $question->_partiallyloaded = true;
 917      }
 918  
 919      return $questions;
 920  }
 921  
 922  /**
 923   * Load a set of questions, given a list of ids. The $join and $extrafields arguments can be used
 924   * together to pull in extra data. See, for example, the usage in mod/quiz/attempt.php, and
 925   * read the code below to see how the SQL is assembled. Throws exceptions on error.
 926   *
 927   * @param array $questionids array of question ids.
 928   * @param string $extrafields extra SQL code to be added to the query.
 929   * @param string $join extra SQL code to be added to the query.
 930   * @return array|string question objects.
 931   */
 932  function question_load_questions($questionids, $extrafields = '', $join = '') {
 933      $questions = question_preload_questions($questionids, $extrafields, $join);
 934  
 935      // Load the question type specific information.
 936      if (!get_question_options($questions)) {
 937          return get_string('questionloaderror', 'question');
 938      }
 939  
 940      return $questions;
 941  }
 942  
 943  /**
 944   * Private function to factor common code out of get_question_options().
 945   *
 946   * @param object $question the question to tidy.
 947   * @param stdClass $category The question_categories record for the given $question.
 948   * @param stdClass[]|null $tagobjects The tags for the given $question.
 949   * @param stdClass[]|null $filtercourses The courses to filter the course tags by.
 950   */
 951  function _tidy_question($question, $category, array $tagobjects = null, array $filtercourses = null): void {
 952      // Convert numeric fields to float. This prevents these being displayed as 1.0000000.
 953      $question->defaultmark += 0;
 954      $question->penalty += 0;
 955  
 956      // Indicate the question is now fully initialised.
 957      if (isset($question->_partiallyloaded)) {
 958          unset($question->_partiallyloaded);
 959      }
 960  
 961      $question->categoryobject = $category;
 962  
 963      // Add any tags we have been passed.
 964      if (!is_null($tagobjects)) {
 965          $categorycontext = context::instance_by_id($category->contextid);
 966          $sortedtagobjects = question_sort_tags($tagobjects, $categorycontext, $filtercourses);
 967          $question->coursetagobjects = $sortedtagobjects->coursetagobjects;
 968          $question->coursetags = $sortedtagobjects->coursetags;
 969          $question->tagobjects = $sortedtagobjects->tagobjects;
 970          $question->tags = $sortedtagobjects->tags;
 971      }
 972  
 973      // Load question-type specific fields.
 974      if (question_bank::is_qtype_installed($question->qtype)) {
 975          question_bank::get_qtype($question->qtype)->get_question_options($question);
 976      } else {
 977          $question->questiontext = html_writer::tag('p', get_string('warningmissingtype',
 978                  'qtype_missingtype')) . $question->questiontext;
 979      }
 980  }
 981  
 982  /**
 983   * Updates the question objects with question type specific
 984   * information by calling {@see get_question_options()}
 985   *
 986   * Can be called either with an array of question objects or with a single
 987   * question object.
 988   *
 989   * @param mixed $questions Either an array of question objects to be updated
 990   *         or just a single question object
 991   * @param bool $loadtags load the question tags from the tags table. Optional, default false.
 992   * @param stdClass[] $filtercourses The courses to filter the course tags by.
 993   * @return bool Indicates success or failure.
 994   */
 995  function get_question_options(&$questions, $loadtags = false, $filtercourses = null) {
 996      global $DB;
 997  
 998      $questionlist = is_array($questions) ? $questions : [$questions];
 999      $categoryids = [];
1000      $questionids = [];
1001  
1002      if (empty($questionlist)) {
1003          return true;
1004      }
1005  
1006      foreach ($questionlist as $question) {
1007          $questionids[] = $question->id;
1008          if (isset($question->category)) {
1009              $qcategoryid = $question->category;
1010          } else {
1011              $qcategoryid = get_question_bank_entry($question->id)->questioncategoryid;
1012              $question->questioncategoryid = $qcategoryid;
1013          }
1014  
1015          if (!in_array($qcategoryid, $categoryids)) {
1016              $categoryids[] = $qcategoryid;
1017          }
1018      }
1019  
1020      $categories = $DB->get_records_list('question_categories', 'id', $categoryids);
1021  
1022      if ($loadtags && core_tag_tag::is_enabled('core_question', 'question')) {
1023          $tagobjectsbyquestion = core_tag_tag::get_items_tags('core_question', 'question', $questionids);
1024      } else {
1025          $tagobjectsbyquestion = null;
1026      }
1027  
1028      foreach ($questionlist as $question) {
1029          if (is_null($tagobjectsbyquestion)) {
1030              $tagobjects = null;
1031          } else {
1032              $tagobjects = $tagobjectsbyquestion[$question->id];
1033          }
1034          $qcategoryid = $question->category ?? $question->questioncategoryid ??
1035              get_question_bank_entry($question->id)->questioncategoryid;
1036  
1037          _tidy_question($question, $categories[$qcategoryid], $tagobjects, $filtercourses);
1038      }
1039  
1040      return true;
1041  }
1042  
1043  /**
1044   * Sort question tags by course or normal tags.
1045   *
1046   * This function also search tag instances that may have a context id that don't match either a course or
1047   * question context and fix the data setting the correct context id.
1048   *
1049   * @param stdClass[] $tagobjects The tags for the given $question.
1050   * @param stdClass $categorycontext The question categories context.
1051   * @param stdClass[]|null $filtercourses The courses to filter the course tags by.
1052   * @return stdClass $sortedtagobjects Sorted tag objects.
1053   */
1054  function question_sort_tags($tagobjects, $categorycontext, $filtercourses = null): stdClass {
1055  
1056      // Questions can have two sets of tag instances. One set at the
1057      // course context level and another at the context the question
1058      // belongs to (e.g. course category, system etc).
1059      $sortedtagobjects = new stdClass();
1060      $sortedtagobjects->coursetagobjects = [];
1061      $sortedtagobjects->coursetags = [];
1062      $sortedtagobjects->tagobjects = [];
1063      $sortedtagobjects->tags = [];
1064      $taginstanceidstonormalise = [];
1065      $filtercoursecontextids = [];
1066      $hasfiltercourses = !empty($filtercourses);
1067  
1068      if ($hasfiltercourses) {
1069          // If we're being asked to filter the course tags by a set of courses
1070          // then get the context ids to filter below.
1071          $filtercoursecontextids = array_map(function($course) {
1072              $coursecontext = context_course::instance($course->id);
1073              return $coursecontext->id;
1074          }, $filtercourses);
1075      }
1076  
1077      foreach ($tagobjects as $tagobject) {
1078          $tagcontextid = $tagobject->taginstancecontextid;
1079          $tagcontext = context::instance_by_id($tagcontextid);
1080          $tagcoursecontext = $tagcontext->get_course_context(false);
1081          // This is a course tag if the tag context is a course context which
1082          // doesn't match the question's context. Any tag in the question context
1083          // is not considered a course tag, it belongs to the question.
1084          $iscoursetag = $tagcoursecontext
1085              && $tagcontext->id == $tagcoursecontext->id
1086              && $tagcontext->id != $categorycontext->id;
1087  
1088          if ($iscoursetag) {
1089              // Any tag instance in a course context level is considered a course tag.
1090              if (!$hasfiltercourses || in_array($tagcontextid, $filtercoursecontextids)) {
1091                  // Add the tag to the list of course tags if we aren't being
1092                  // asked to filter or if this tag is in the list of courses
1093                  // we're being asked to filter by.
1094                  $sortedtagobjects->coursetagobjects[] = $tagobject;
1095                  $sortedtagobjects->coursetags[$tagobject->id] = $tagobject->get_display_name();
1096              }
1097          } else {
1098              // All non course context level tag instances or tags in the question
1099              // context belong to the context that the question was created in.
1100              $sortedtagobjects->tagobjects[] = $tagobject;
1101              $sortedtagobjects->tags[$tagobject->id] = $tagobject->get_display_name();
1102  
1103              // Due to legacy tag implementations that don't force the recording
1104              // of a context id, some tag instances may have context ids that don't
1105              // match either a course context or the question context. In this case
1106              // we should take the opportunity to fix up the data and set the correct
1107              // context id.
1108              if ($tagcontext->id != $categorycontext->id) {
1109                  $taginstanceidstonormalise[] = $tagobject->taginstanceid;
1110                  // Update the object properties to reflect the DB update that will
1111                  // happen below.
1112                  $tagobject->taginstancecontextid = $categorycontext->id;
1113              }
1114          }
1115      }
1116  
1117      if (!empty($taginstanceidstonormalise)) {
1118          // If we found any tag instances with incorrect context id data then we can
1119          // correct those values now by setting them to the question context id.
1120          core_tag_tag::change_instances_context($taginstanceidstonormalise, $categorycontext);
1121      }
1122  
1123      return $sortedtagobjects;
1124  }
1125  
1126  /**
1127   * Print the icon for the question type
1128   *
1129   * @param object $question The question object for which the icon is required.
1130   *       Only $question->qtype is used.
1131   * @return string the HTML for the img tag.
1132   */
1133  function print_question_icon($question): string {
1134      global $PAGE;
1135  
1136      if (gettype($question->qtype) == 'object') {
1137          $qtype = $question->qtype->name();
1138      } else {
1139          // Assume string.
1140          $qtype = $question->qtype;
1141      }
1142  
1143      return $PAGE->get_renderer('question', 'bank')->qtype_icon($qtype);
1144  }
1145  
1146  // CATEGORY FUNCTIONS.
1147  
1148  /**
1149   * Returns the categories with their names ordered following parent-child relationships.
1150   * finally it tries to return pending categories (those being orphaned, whose parent is
1151   * incorrect) to avoid missing any category from original array.
1152   *
1153   * @param array $categories
1154   * @param int $id
1155   * @param int $level
1156   * @return array
1157   */
1158  function sort_categories_by_tree(&$categories, $id = 0, $level = 1): array {
1159      global $DB;
1160  
1161      $children = [];
1162      $keys = array_keys($categories);
1163  
1164      foreach ($keys as $key) {
1165          if (!isset($categories[$key]->processed) && $categories[$key]->parent == $id) {
1166              $children[$key] = $categories[$key];
1167              $categories[$key]->processed = true;
1168              $children = $children + sort_categories_by_tree(
1169                      $categories, $children[$key]->id, $level + 1);
1170          }
1171      }
1172      // If level = 1, we have finished, try to look for non processed categories (bad parent) and sort them too.
1173      if ($level == 1) {
1174          foreach ($keys as $key) {
1175              // If not processed and it's a good candidate to start (because its parent doesn't exist in the course).
1176              if (!isset($categories[$key]->processed) && !$DB->record_exists('question_categories',
1177                      array('contextid' => $categories[$key]->contextid,
1178                              'id' => $categories[$key]->parent))) {
1179                  $children[$key] = $categories[$key];
1180                  $categories[$key]->processed = true;
1181                  $children = $children + sort_categories_by_tree(
1182                          $categories, $children[$key]->id, $level + 1);
1183              }
1184          }
1185      }
1186      return $children;
1187  }
1188  
1189  /**
1190   * Get the default category for the context.
1191   *
1192   * @param integer $contextid a context id.
1193   * @return object|bool the default question category for that context, or false if none.
1194   */
1195  function question_get_default_category($contextid) {
1196      global $DB;
1197      $category = $DB->get_records_select('question_categories', 'contextid = ? AND parent <> 0',
1198                                          [$contextid], 'id', '*', 0, 1);
1199      if (!empty($category)) {
1200          return reset($category);
1201      } else {
1202          return false;
1203      }
1204  }
1205  
1206  /**
1207   * Gets the top category in the given context.
1208   * This function can optionally create the top category if it doesn't exist.
1209   *
1210   * @param int $contextid A context id.
1211   * @param bool $create Whether create a top category if it doesn't exist.
1212   * @return bool|stdClass The top question category for that context, or false if none.
1213   */
1214  function question_get_top_category($contextid, $create = false) {
1215      global $DB;
1216      $category = $DB->get_record('question_categories', ['contextid' => $contextid, 'parent' => 0]);
1217  
1218      if (!$category && $create) {
1219          // We need to make one.
1220          $category = new stdClass();
1221          $category->name = 'top'; // A non-real name for the top category. It will be localised at the display time.
1222          $category->info = '';
1223          $category->contextid = $contextid;
1224          $category->parent = 0;
1225          $category->sortorder = 0;
1226          $category->stamp = make_unique_id_code();
1227          $category->id = $DB->insert_record('question_categories', $category);
1228      }
1229  
1230      return $category;
1231  }
1232  
1233  /**
1234   * Gets the list of top categories in the given contexts in the array("categoryid,categorycontextid") format.
1235   *
1236   * @param array $contextids List of context ids
1237   * @return array
1238   */
1239  function question_get_top_categories_for_contexts($contextids): array {
1240      global $DB;
1241  
1242      $concatsql = $DB->sql_concat_join("','", ['id', 'contextid']);
1243      list($insql, $params) = $DB->get_in_or_equal($contextids);
1244      $sql = "SELECT $concatsql
1245                FROM {question_categories}
1246               WHERE contextid $insql
1247                 AND parent = 0";
1248  
1249      $topcategories = $DB->get_fieldset_sql($sql, $params);
1250  
1251      return $topcategories;
1252  }
1253  
1254  /**
1255   * Gets the default category in the most specific context.
1256   * If no categories exist yet then default ones are created in all contexts.
1257   *
1258   * @param array $contexts  The context objects for this context and all parent contexts.
1259   * @return object The default category - the category in the course context
1260   */
1261  function question_make_default_categories($contexts): object {
1262      global $DB;
1263      static $preferredlevels = array(
1264          CONTEXT_COURSE => 4,
1265          CONTEXT_MODULE => 3,
1266          CONTEXT_COURSECAT => 2,
1267          CONTEXT_SYSTEM => 1,
1268      );
1269  
1270      $toreturn = null;
1271      $preferredness = 0;
1272      // If it already exists, just return it.
1273      foreach ($contexts as $key => $context) {
1274          $topcategory = question_get_top_category($context->id, true);
1275          if (!$exists = $DB->record_exists("question_categories",
1276                  array('contextid' => $context->id, 'parent' => $topcategory->id))) {
1277              // Otherwise, we need to make one.
1278              $category = new stdClass();
1279              $contextname = $context->get_context_name(false, true);
1280              // Max length of name field is 255.
1281              $category->name = shorten_text(get_string('defaultfor', 'question', $contextname), 255);
1282              $category->info = get_string('defaultinfofor', 'question', $contextname);
1283              $category->contextid = $context->id;
1284              $category->parent = $topcategory->id;
1285              // By default, all categories get this number, and are sorted alphabetically.
1286              $category->sortorder = 999;
1287              $category->stamp = make_unique_id_code();
1288              $category->id = $DB->insert_record('question_categories', $category);
1289          } else {
1290              $category = question_get_default_category($context->id);
1291          }
1292          $thispreferredness = $preferredlevels[$context->contextlevel];
1293          if (has_any_capability(array('moodle/question:usemine', 'moodle/question:useall'), $context)) {
1294              $thispreferredness += 10;
1295          }
1296          if ($thispreferredness > $preferredness) {
1297              $toreturn = $category;
1298              $preferredness = $thispreferredness;
1299          }
1300      }
1301  
1302      if (!is_null($toreturn)) {
1303          $toreturn = clone($toreturn);
1304      }
1305      return $toreturn;
1306  }
1307  
1308  /**
1309   * Get the list of categories.
1310   *
1311   * @param int $categoryid
1312   * @return array of question category ids of the category and all subcategories.
1313   */
1314  function question_categorylist($categoryid): array {
1315      global $DB;
1316  
1317      // Final list of category IDs.
1318      $categorylist = array();
1319  
1320      // A list of category IDs to check for any sub-categories.
1321      $subcategories = array($categoryid);
1322  
1323      while ($subcategories) {
1324          foreach ($subcategories as $subcategory) {
1325              // If anything from the temporary list was added already, then we have a loop.
1326              if (isset($categorylist[$subcategory])) {
1327                  throw new coding_exception("Category id=$subcategory is already on the list - loop of categories detected.");
1328              }
1329              $categorylist[$subcategory] = $subcategory;
1330          }
1331  
1332          list ($in, $params) = $DB->get_in_or_equal($subcategories);
1333  
1334          $subcategories = $DB->get_records_select_menu('question_categories', "parent $in", $params,
1335                                                      null, 'id,id AS id2');
1336      }
1337  
1338      return $categorylist;
1339  }
1340  
1341  /**
1342   * Get all parent categories of a given question category in decending order.
1343   * @param int $categoryid for which you want to find the parents.
1344   * @return array of question category ids of all parents categories.
1345   */
1346  function question_categorylist_parents(int $categoryid): array {
1347      global $DB;
1348      $parent = $DB->get_field('question_categories', 'parent', array('id' => $categoryid));
1349      if (!$parent) {
1350          return [];
1351      }
1352      $categorylist = [$parent];
1353      $currentid = $parent;
1354      while ($currentid) {
1355          $currentid = $DB->get_field('question_categories', 'parent', array('id' => $currentid));
1356          if ($currentid) {
1357              $categorylist[] = $currentid;
1358          }
1359      }
1360      // Present the list in decending order (the top category at the top).
1361      $categorylist = array_reverse($categorylist);
1362      return $categorylist;
1363  }
1364  
1365  // Import/Export Functions.
1366  
1367  /**
1368   * Get list of available import or export formats
1369   * @param string $type 'import' if import list, otherwise export list assumed
1370   * @return array sorted list of import/export formats available
1371   */
1372  function get_import_export_formats($type): array {
1373      global $CFG;
1374      require_once($CFG->dirroot . '/question/format.php');
1375  
1376      $formatclasses = core_component::get_plugin_list_with_class('qformat', '', 'format.php');
1377  
1378      $fileformatname = array();
1379      foreach ($formatclasses as $component => $formatclass) {
1380  
1381          $format = new $formatclass();
1382          if ($type == 'import') {
1383              $provided = $format->provide_import();
1384          } else {
1385              $provided = $format->provide_export();
1386          }
1387  
1388          if ($provided) {
1389              list($notused, $fileformat) = explode('_', $component, 2);
1390              $fileformatnames[$fileformat] = get_string('pluginname', $component);
1391          }
1392      }
1393  
1394      core_collator::asort($fileformatnames);
1395      return $fileformatnames;
1396  }
1397  
1398  
1399  /**
1400   * Create a reasonable default file name for exporting questions from a particular
1401   * category.
1402   * @param object $course the course the questions are in.
1403   * @param object $category the question category.
1404   * @return string the filename.
1405   */
1406  function question_default_export_filename($course, $category): string {
1407      // We build a string that is an appropriate name (questions) from the lang pack,
1408      // then the corse shortname, then the question category name, then a timestamp.
1409  
1410      $base = clean_filename(get_string('exportfilename', 'question'));
1411  
1412      $dateformat = str_replace(' ', '_', get_string('exportnameformat', 'question'));
1413      $timestamp = clean_filename(userdate(time(), $dateformat, 99, false));
1414  
1415      $shortname = clean_filename($course->shortname);
1416      if ($shortname == '' || $shortname == '_' ) {
1417          $shortname = $course->id;
1418      }
1419  
1420      $categoryname = clean_filename(format_string($category->name));
1421  
1422      return "{$base}-{$shortname}-{$categoryname}-{$timestamp}";
1423  }
1424  
1425  /**
1426   * Check capability on category.
1427   *
1428   * @param int|stdClass|question_definition $questionorid object or id.
1429   *      If an object is passed, it should include ->contextid and ->createdby.
1430   * @param string $cap 'add', 'edit', 'view', 'use', 'move' or 'tag'.
1431   * @param int $notused no longer used.
1432   * @return bool this user has the capability $cap for this question $question?
1433   */
1434  function question_has_capability_on($questionorid, $cap, $notused = -1): bool {
1435      global $USER, $DB;
1436  
1437      if (is_numeric($questionorid)) {
1438          $questionid = (int)$questionorid;
1439      } else if (is_object($questionorid)) {
1440          // All we really need in this function is the contextid and author of the question.
1441          // We won't bother fetching other details of the question if these 2 fields are provided.
1442          if (isset($questionorid->contextid) && isset($questionorid->createdby)) {
1443              $question = $questionorid;
1444          } else if (!empty($questionorid->id)) {
1445              $questionid = $questionorid->id;
1446          }
1447      }
1448  
1449      // At this point, either $question or $questionid is expected to be set.
1450      if (isset($questionid)) {
1451          try {
1452              $question = question_bank::load_question_data($questionid);
1453          } catch (Exception $e) {
1454              // Let's log the exception for future debugging,
1455              // but not during Behat, or we can't test these cases.
1456              if (!defined('BEHAT_SITE_RUNNING')) {
1457                  debugging($e->getMessage(), DEBUG_NORMAL, $e->getTrace());
1458              }
1459  
1460              $sql = 'SELECT q.id,
1461                             q.createdby,
1462                             qc.contextid
1463                        FROM {question} q
1464                        JOIN {question_versions} qv
1465                          ON qv.questionid = q.id
1466                        JOIN {question_bank_entries} qbe
1467                          ON qbe.id = qv.questionbankentryid
1468                        JOIN {question_categories} qc
1469                          ON qc.id = qbe.questioncategoryid
1470                       WHERE q.id = :id';
1471  
1472              // Well, at least we tried. Seems that we really have to read from DB.
1473              $question = $DB->get_record_sql($sql, ['id' => $questionid]);
1474          }
1475      }
1476  
1477      if (!isset($question)) {
1478          throw new coding_exception('$questionorid parameter needs to be an integer or an object.');
1479      }
1480  
1481      $context = context::instance_by_id($question->contextid);
1482  
1483      // These are existing questions capabilities that are set per category.
1484      // Each of these has a 'mine' and 'all' version that is appended to the capability name.
1485      $capabilitieswithallandmine = ['edit' => 1, 'view' => 1, 'use' => 1, 'move' => 1, 'tag' => 1, 'comment' => 1];
1486  
1487      if (!isset($capabilitieswithallandmine[$cap])) {
1488          return has_capability('moodle/question:' . $cap, $context);
1489      } else {
1490          return has_capability('moodle/question:' . $cap . 'all', $context) ||
1491              ($question->createdby == $USER->id && has_capability('moodle/question:' . $cap . 'mine', $context));
1492      }
1493  }
1494  
1495  /**
1496   * Require capability on question.
1497   *
1498   * @param int|stdClass|question_definition $question object or id.
1499   *      If an object is passed, it should include ->contextid and ->createdby.
1500   * @param string $cap 'add', 'edit', 'view', 'use', 'move' or 'tag'.
1501   * @return bool true if the user has the capability. Throws exception if not.
1502   */
1503  function question_require_capability_on($question, $cap): bool {
1504      if (!question_has_capability_on($question, $cap)) {
1505          throw new moodle_exception('nopermissions', '', '', $cap);
1506      }
1507      return true;
1508  }
1509  
1510  /**
1511   * Gets the question edit url.
1512   *
1513   * @param object $context a context
1514   * @return string|bool A URL for editing questions in this context.
1515   */
1516  function question_edit_url($context) {
1517      global $CFG, $SITE;
1518      if (!has_any_capability(question_get_question_capabilities(), $context)) {
1519          return false;
1520      }
1521      $baseurl = $CFG->wwwroot . '/question/edit.php?';
1522      $defaultcategory = question_get_default_category($context->id);
1523      if ($defaultcategory) {
1524          $baseurl .= 'cat=' . $defaultcategory->id . ',' . $context->id . '&amp;';
1525      }
1526      switch ($context->contextlevel) {
1527          case CONTEXT_SYSTEM:
1528              return $baseurl . 'courseid=' . $SITE->id;
1529          case CONTEXT_COURSECAT:
1530              // This is nasty, becuase we can only edit questions in a course
1531              // context at the moment, so for now we just return false.
1532              return false;
1533          case CONTEXT_COURSE:
1534              return $baseurl . 'courseid=' . $context->instanceid;
1535          case CONTEXT_MODULE:
1536              return $baseurl . 'cmid=' . $context->instanceid;
1537      }
1538  
1539  }
1540  
1541  /**
1542   * Adds question bank setting links to the given navigation node if caps are met
1543   * and loads the navigation from the plugins.
1544   * Qbank plugins can extend the navigation_plugin_base and add their own navigation node,
1545   * this method will help to autoload those nodes in the question bank navigation.
1546   *
1547   * @param navigation_node $navigationnode The navigation node to add the question branch to
1548   * @param object $context
1549   * @param string $baseurl the url of the base where the api is implemented from
1550   * @return navigation_node Returns the question branch that was added
1551   */
1552  function question_extend_settings_navigation(navigation_node $navigationnode, $context, $baseurl = '/question/edit.php') {
1553      global $PAGE;
1554  
1555      if ($context->contextlevel == CONTEXT_COURSE) {
1556          $params = ['courseid' => $context->instanceid];
1557      } else if ($context->contextlevel == CONTEXT_MODULE) {
1558          $params = ['cmid' => $context->instanceid];
1559      } else {
1560          return;
1561      }
1562  
1563      if (($cat = $PAGE->url->param('cat')) && preg_match('~\d+,\d+~', $cat)) {
1564          $params['cat'] = $cat;
1565      }
1566  
1567      $questionnode = $navigationnode->add(get_string('questionbank', 'question'),
1568              new moodle_url($baseurl, $params), navigation_node::TYPE_CONTAINER, null, 'questionbank');
1569  
1570      $corenavigations = [
1571              'questions' => [
1572                      'title' => get_string('questions', 'question'),
1573                      'url' => new moodle_url($baseurl)
1574              ],
1575              'categories' => [],
1576              'import' => [],
1577              'export' => []
1578      ];
1579  
1580      $plugins = \core_component::get_plugin_list_with_class('qbank', 'plugin_feature', 'plugin_feature.php');
1581      foreach ($plugins as $componentname => $plugin) {
1582          $pluginentrypoint = new $plugin();
1583          $pluginentrypointobject = $pluginentrypoint->get_navigation_node();
1584          // Don't need the plugins without navigation node.
1585          if ($pluginentrypointobject === null) {
1586              unset($plugins[$componentname]);
1587              continue;
1588          }
1589          foreach ($corenavigations as $key => $corenavigation) {
1590              if ($pluginentrypointobject->get_navigation_key() === $key) {
1591                  unset($plugins[$componentname]);
1592                  if (!\core\plugininfo\qbank::is_plugin_enabled($componentname)) {
1593                      unset($corenavigations[$key]);
1594                      break;
1595                  }
1596                  $corenavigations[$key] = [
1597                      'title' => $pluginentrypointobject->get_navigation_title(),
1598                      'url'   => $pluginentrypointobject->get_navigation_url()
1599                  ];
1600              }
1601          }
1602      }
1603  
1604      // Mitigate the risk of regression.
1605      foreach ($corenavigations as $node => $corenavigation) {
1606          if (empty($corenavigation)) {
1607              unset($corenavigations[$node]);
1608          }
1609      }
1610  
1611      // Community/additional plugins have navigation node.
1612      $pluginnavigations = [];
1613      foreach ($plugins as $componentname => $plugin) {
1614          $pluginentrypoint = new $plugin();
1615          $pluginentrypointobject = $pluginentrypoint->get_navigation_node();
1616          // Don't need the plugins without navigation node.
1617          if ($pluginentrypointobject === null || !\core\plugininfo\qbank::is_plugin_enabled($componentname)) {
1618              unset($plugins[$componentname]);
1619              continue;
1620          }
1621          $pluginnavigations[$pluginentrypointobject->get_navigation_key()] = [
1622              'title' => $pluginentrypointobject->get_navigation_title(),
1623              'url'   => $pluginentrypointobject->get_navigation_url(),
1624              'capabilities' => $pluginentrypointobject->get_navigation_capabilities()
1625          ];
1626      }
1627  
1628      $contexts = new core_question\local\bank\question_edit_contexts($context);
1629      foreach ($corenavigations as $key => $corenavigation) {
1630          if ($contexts->have_one_edit_tab_cap($key)) {
1631              $questionnode->add($corenavigation['title'], new moodle_url(
1632                      $corenavigation['url'], $params), navigation_node::TYPE_SETTING, null, $key);
1633          }
1634      }
1635  
1636      foreach ($pluginnavigations as $key => $pluginnavigation) {
1637          if (is_array($pluginnavigation['capabilities'])) {
1638              if (!$contexts->have_one_cap($pluginnavigation['capabilities'])) {
1639                  continue;
1640              }
1641          }
1642          $questionnode->add($pluginnavigation['title'], new moodle_url(
1643                  $pluginnavigation['url'], $params), navigation_node::TYPE_SETTING, null, $key);
1644      }
1645  
1646      return $questionnode;
1647  }
1648  
1649  /**
1650   * Get the array of capabilities for question.
1651   *
1652   * @return array all the capabilities that relate to accessing particular questions.
1653   */
1654  function question_get_question_capabilities(): array {
1655      return [
1656          'moodle/question:add',
1657          'moodle/question:editmine',
1658          'moodle/question:editall',
1659          'moodle/question:viewmine',
1660          'moodle/question:viewall',
1661          'moodle/question:usemine',
1662          'moodle/question:useall',
1663          'moodle/question:movemine',
1664          'moodle/question:moveall',
1665          'moodle/question:tagmine',
1666          'moodle/question:tagall',
1667          'moodle/question:commentmine',
1668          'moodle/question:commentall',
1669      ];
1670  }
1671  
1672  /**
1673   * Get the question bank caps.
1674   *
1675   * @return array all the question bank capabilities.
1676   */
1677  function question_get_all_capabilities(): array {
1678      $caps = question_get_question_capabilities();
1679      $caps[] = 'moodle/question:managecategory';
1680      $caps[] = 'moodle/question:flag';
1681      return $caps;
1682  }
1683  
1684  /**
1685   * Helps call file_rewrite_pluginfile_urls with the right parameters.
1686   *
1687   * @package  core_question
1688   * @category files
1689   * @param string $text text being processed
1690   * @param string $file the php script used to serve files
1691   * @param int $contextid context ID
1692   * @param string $component component
1693   * @param string $filearea filearea
1694   * @param array $ids other IDs will be used to check file permission
1695   * @param int $itemid item ID
1696   * @param array $options options
1697   * @return string
1698   */
1699  function question_rewrite_question_urls($text, $file, $contextid, $component, $filearea,
1700                                          array $ids, $itemid, array $options=null): string {
1701  
1702      $idsstr = '';
1703      if (!empty($ids)) {
1704          $idsstr .= implode('/', $ids);
1705      }
1706      if ($itemid !== null) {
1707          $idsstr .= '/' . $itemid;
1708      }
1709      return file_rewrite_pluginfile_urls($text, $file, $contextid, $component,
1710              $filearea, $idsstr, $options);
1711  }
1712  
1713  /**
1714   * Rewrite the PLUGINFILE urls in part of the content of a question, for use when
1715   * viewing the question outside an attempt (for example, in the question bank
1716   * listing or in the quiz statistics report).
1717   *
1718   * @param string $text the question text.
1719   * @param int $questionid the question id.
1720   * @param int $filecontextid the context id of the question being displayed.
1721   * @param string $filecomponent the component that owns the file area.
1722   * @param string $filearea the file area name.
1723   * @param int|null $itemid the file's itemid
1724   * @param int $previewcontextid the context id where the preview is being displayed.
1725   * @param string $previewcomponent component responsible for displaying the preview.
1726   * @param array $options text and file options ('forcehttps'=>false)
1727   * @return string $questiontext with URLs rewritten.
1728   */
1729  function question_rewrite_question_preview_urls($text, $questionid, $filecontextid, $filecomponent, $filearea, $itemid,
1730                                                  $previewcontextid, $previewcomponent, $options = null): string {
1731  
1732      $path = "preview/$previewcontextid/$previewcomponent/$questionid";
1733      if ($itemid) {
1734          $path .= '/' . $itemid;
1735      }
1736  
1737      return file_rewrite_pluginfile_urls($text, 'pluginfile.php', $filecontextid,
1738              $filecomponent, $filearea, $path, $options);
1739  }
1740  
1741  /**
1742   * Called by pluginfile.php to serve files related to the 'question' core
1743   * component and for files belonging to qtypes.
1744   *
1745   * For files that relate to questions in a question_attempt, then we delegate to
1746   * a function in the component that owns the attempt (for example in the quiz,
1747   * or in core question preview) to get necessary inforation.
1748   *
1749   * (Note that, at the moment, all question file areas relate to questions in
1750   * attempts, so the If at the start of the last paragraph is always true.)
1751   *
1752   * Does not return, either calls send_file_not_found(); or serves the file.
1753   *
1754   * @category files
1755   * @param stdClass $course course settings object
1756   * @param stdClass $context context object
1757   * @param string $component the name of the component we are serving files for.
1758   * @param string $filearea the name of the file area.
1759   * @param array $args the remaining bits of the file path.
1760   * @param bool $forcedownload whether the user must be forced to download the file.
1761   * @param array $options additional options affecting the file serving
1762   * @return array|bool
1763   */
1764  function question_pluginfile($course, $context, $component, $filearea, $args, $forcedownload, $options = []) {
1765      global $DB, $CFG;
1766  
1767      // Special case, sending a question bank export.
1768      if ($filearea === 'export') {
1769          list($context, $course, $cm) = get_context_info_array($context->id);
1770          require_login($course, false, $cm);
1771  
1772          require_once($CFG->dirroot . '/question/editlib.php');
1773          $contexts = new core_question\local\bank\question_edit_contexts($context);
1774          // Check export capability.
1775          $contexts->require_one_edit_tab_cap('export');
1776          $categoryid = (int)array_shift($args);
1777          $format      = array_shift($args);
1778          $cattofile   = array_shift($args);
1779          $contexttofile = array_shift($args);
1780          $filename    = array_shift($args);
1781  
1782          // Load parent class for import/export.
1783          require_once($CFG->dirroot . '/question/format.php');
1784          require_once($CFG->dirroot . '/question/editlib.php');
1785          require_once($CFG->dirroot . '/question/format/' . $format . '/format.php');
1786  
1787          $classname = 'qformat_' . $format;
1788          if (!class_exists($classname)) {
1789              send_file_not_found();
1790          }
1791  
1792          $qformat = new $classname();
1793  
1794          if (!$category = $DB->get_record('question_categories', array('id' => $categoryid))) {
1795              send_file_not_found();
1796          }
1797  
1798          $qformat->setCategory($category);
1799          $qformat->setContexts($contexts->having_one_edit_tab_cap('export'));
1800          $qformat->setCourse($course);
1801  
1802          if ($cattofile == 'withcategories') {
1803              $qformat->setCattofile(true);
1804          } else {
1805              $qformat->setCattofile(false);
1806          }
1807  
1808          if ($contexttofile == 'withcontexts') {
1809              $qformat->setContexttofile(true);
1810          } else {
1811              $qformat->setContexttofile(false);
1812          }
1813  
1814          if (!$qformat->exportpreprocess()) {
1815              send_file_not_found();
1816              throw new moodle_exception('exporterror', 'question', $thispageurl->out());
1817          }
1818  
1819          // Export data to moodle file pool.
1820          if (!$content = $qformat->exportprocess()) {
1821              send_file_not_found();
1822          }
1823  
1824          send_file($content, $filename, 0, 0, true, true, $qformat->mime_type());
1825      }
1826  
1827      // Normal case, a file belonging to a question.
1828      $qubaidorpreview = array_shift($args);
1829  
1830      // Two sub-cases: 1. A question being previewed outside an attempt/usage.
1831      if ($qubaidorpreview === 'preview') {
1832          $previewcontextid = (int)array_shift($args);
1833          $previewcomponent = array_shift($args);
1834          $questionid = (int) array_shift($args);
1835          $previewcontext = context_helper::instance_by_id($previewcontextid);
1836  
1837          $result = component_callback($previewcomponent, 'question_preview_pluginfile', array(
1838                  $previewcontext, $questionid,
1839                  $context, $component, $filearea, $args,
1840                  $forcedownload, $options), 'callbackmissing');
1841  
1842          if ($result === 'callbackmissing') {
1843              throw new coding_exception("Component {$previewcomponent} does not define the callback " .
1844                      "{$previewcomponent}_question_preview_pluginfile callback. " .
1845                      "Which is required if you are using question_rewrite_question_preview_urls.", DEBUG_DEVELOPER);
1846          }
1847  
1848          send_file_not_found();
1849      }
1850  
1851      // 2. A question being attempted in the normal way.
1852      $qubaid = (int)$qubaidorpreview;
1853      $slot = (int)array_shift($args);
1854  
1855      $module = $DB->get_field('question_usages', 'component',
1856              array('id' => $qubaid));
1857      if (!$module) {
1858          send_file_not_found();
1859      }
1860  
1861      if ($module === 'core_question_preview') {
1862          return qbank_previewquestion\helper::question_preview_question_pluginfile($course, $context,
1863                  $component, $filearea, $qubaid, $slot, $args, $forcedownload, $options);
1864  
1865      } else {
1866          $dir = core_component::get_component_directory($module);
1867          if (!file_exists("$dir/lib.php")) {
1868              send_file_not_found();
1869          }
1870          include_once("$dir/lib.php");
1871  
1872          $filefunction = $module . '_question_pluginfile';
1873          if (function_exists($filefunction)) {
1874              $filefunction($course, $context, $component, $filearea, $qubaid, $slot,
1875                  $args, $forcedownload, $options);
1876          }
1877  
1878          // Okay, we're here so lets check for function without 'mod_'.
1879          if (strpos($module, 'mod_') === 0) {
1880              $filefunctionold  = substr($module, 4) . '_question_pluginfile';
1881              if (function_exists($filefunctionold)) {
1882                  $filefunctionold($course, $context, $component, $filearea, $qubaid, $slot,
1883                      $args, $forcedownload, $options);
1884              }
1885          }
1886  
1887          send_file_not_found();
1888      }
1889  }
1890  
1891  /**
1892   * Serve questiontext files in the question text when they are displayed in this report.
1893   *
1894   * @param context $previewcontext the context in which the preview is happening.
1895   * @param int $questionid the question id.
1896   * @param context $filecontext the file (question) context.
1897   * @param string $filecomponent the component the file belongs to.
1898   * @param string $filearea the file area.
1899   * @param array $args remaining file args.
1900   * @param bool $forcedownload
1901   * @param array $options additional options affecting the file serving.
1902   */
1903  function core_question_question_preview_pluginfile($previewcontext, $questionid, $filecontext, $filecomponent,
1904                                                      $filearea, $args, $forcedownload, $options = []): void {
1905      global $DB;
1906      $sql = 'SELECT q.*,
1907                     qc.contextid
1908                FROM {question} q
1909                JOIN {question_versions} qv
1910                  ON qv.questionid = q.id
1911                JOIN {question_bank_entries} qbe
1912                  ON qbe.id = qv.questionbankentryid
1913                JOIN {question_categories} qc
1914                  ON qc.id = qbe.questioncategoryid
1915               WHERE q.id = :id
1916                 AND qc.contextid = :contextid';
1917  
1918      // Verify that contextid matches the question.
1919      $question = $DB->get_record_sql($sql, ['id' => $questionid, 'contextid' => $filecontext->id], MUST_EXIST);
1920  
1921      // Check the capability.
1922      list($context, $course, $cm) = get_context_info_array($previewcontext->id);
1923      require_login($course, false, $cm);
1924  
1925      question_require_capability_on($question, 'use');
1926  
1927      $fs = get_file_storage();
1928      $relativepath = implode('/', $args);
1929      $fullpath = "/{$filecontext->id}/{$filecomponent}/{$filearea}/{$relativepath}";
1930      if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
1931          send_file_not_found();
1932      }
1933  
1934      send_stored_file($file, 0, 0, $forcedownload, $options);
1935  }
1936  
1937  /**
1938   * Return a list of page types
1939   * @param string $pagetype current page type
1940   * @param stdClass $parentcontext Block's parent context
1941   * @param stdClass $currentcontext Current context of block
1942   * @return array
1943   */
1944  function question_page_type_list($pagetype, $parentcontext, $currentcontext): array {
1945      global $CFG;
1946      $types = [
1947          'question-*' => get_string('page-question-x', 'question'),
1948          'question-edit' => get_string('page-question-edit', 'question'),
1949          'question-category' => get_string('page-question-category', 'question'),
1950          'question-export' => get_string('page-question-export', 'question'),
1951          'question-import' => get_string('page-question-import', 'question')
1952      ];
1953      if ($currentcontext->contextlevel == CONTEXT_COURSE) {
1954          require_once($CFG->dirroot . '/course/lib.php');
1955          return array_merge(course_page_type_list($pagetype, $parentcontext, $currentcontext), $types);
1956      } else {
1957          return $types;
1958      }
1959  }
1960  
1961  /**
1962   * Does an activity module use the question bank?
1963   *
1964   * @param string $modname The name of the module (without mod_ prefix).
1965   * @return bool true if the module uses questions.
1966   */
1967  function question_module_uses_questions($modname): bool {
1968      if (plugin_supports('mod', $modname, FEATURE_USES_QUESTIONS)) {
1969          return true;
1970      }
1971  
1972      $component = 'mod_'.$modname;
1973      if (component_callback_exists($component, 'question_pluginfile')) {
1974          debugging("{$component} uses questions but doesn't declare FEATURE_USES_QUESTIONS", DEBUG_DEVELOPER);
1975          return true;
1976      }
1977  
1978      return false;
1979  }
1980  
1981  /**
1982   * If $oldidnumber ends in some digits then return the next available idnumber of the same form.
1983   *
1984   * So idnum -> null (no digits at the end) idnum0099 -> idnum0100 (if that is unused,
1985   * else whichever of idnum0101, idnume0102, ... is unused. idnum9 -> idnum10.
1986   *
1987   * @param string|null $oldidnumber a question idnumber, or can be null.
1988   * @param int $categoryid a question category id.
1989   * @return string|null suggested new idnumber for a question in that category, or null if one cannot be found.
1990   */
1991  function core_question_find_next_unused_idnumber(?string $oldidnumber, int $categoryid): ?string {
1992      global $DB;
1993  
1994      // The the old idnumber is not of the right form, bail now.
1995      if ($oldidnumber === null || !preg_match('~\d+$~', $oldidnumber, $matches)) {
1996          return null;
1997      }
1998  
1999      // Find all used idnumbers in one DB query.
2000      $usedidnumbers = $DB->get_records_select_menu('question_bank_entries', 'questioncategoryid = ? AND idnumber IS NOT NULL',
2001              [$categoryid], '', 'idnumber, 1');
2002  
2003      // Find the next unused idnumber.
2004      $numberbit = 'X' . $matches[0]; // Need a string here so PHP does not do '0001' + 1 = 2.
2005      $stem = substr($oldidnumber, 0, -strlen($matches[0]));
2006      do {
2007  
2008          // If we have got to something9999, insert an extra digit before incrementing.
2009          if (preg_match('~^(.*[^0-9])(9+)$~', $numberbit, $matches)) {
2010              $numberbit = $matches[1] . '0' . $matches[2];
2011          }
2012          $numberbit++;
2013          $newidnumber = $stem . substr($numberbit, 1);
2014      } while (isset($usedidnumbers[$newidnumber]));
2015  
2016      return (string) $newidnumber;
2017  }
2018  
2019  /**
2020   * Get the question_bank_entry object given a question id.
2021   *
2022   * @param int $questionid Question id.
2023   * @return false|mixed
2024   * @throws dml_exception
2025   */
2026  function get_question_bank_entry(int $questionid): object {
2027      global $DB;
2028  
2029      $sql = "SELECT qbe.*
2030                FROM {question} q
2031                JOIN {question_versions} qv ON qv.questionid = q.id
2032                JOIN {question_bank_entries} qbe ON qbe.id = qv.questionbankentryid
2033               WHERE q.id = :id";
2034  
2035      $qbankentry = $DB->get_record_sql($sql, ['id' => $questionid]);
2036  
2037      return $qbankentry;
2038  }
2039  
2040  /**
2041   * Get the question versions given a question id in a descending sort .
2042   *
2043   * @param int $questionid Question id.
2044   * @return array
2045   * @throws dml_exception
2046   */
2047  function get_question_version($questionid): array {
2048      global $DB;
2049  
2050      $version = $DB->get_records('question_versions', ['questionid' => $questionid]);
2051      krsort($version);
2052  
2053      return $version;
2054  }
2055  
2056  /**
2057   * Get the next version number to create base on a Question bank entry id.
2058   *
2059   * @param int $questionbankentryid Question bank entry id.
2060   * @return int next version number.
2061   * @throws dml_exception
2062   */
2063  function get_next_version(int $questionbankentryid): int {
2064      global $DB;
2065  
2066      $sql = "SELECT MAX(qv.version)
2067                FROM {question_versions} qv
2068                JOIN {question_bank_entries} qbe ON qbe.id = qv.questionbankentryid
2069               WHERE qbe.id = :id";
2070  
2071      $nextversion = $DB->get_field_sql($sql, ['id' => $questionbankentryid]);
2072  
2073      if ($nextversion) {
2074          return (int)$nextversion + 1;
2075      }
2076  
2077      return 1;
2078  }
2079  
2080  /**
2081   * Checks if question is the latest version.
2082   *
2083   * @param string $version Question version to check.
2084   * @param string $questionbankentryid Entry to check against.
2085   * @return bool
2086   */
2087  function is_latest(string $version, string $questionbankentryid) : bool {
2088      global $DB;
2089  
2090      $sql = 'SELECT MAX(version) AS max
2091                    FROM {question_versions}
2092                   WHERE questionbankentryid = ?';
2093      $latestversion = $DB->get_record_sql($sql, [$questionbankentryid]);
2094  
2095      if (isset($latestversion->max)) {
2096          return ($version === $latestversion->max) ? true : false;
2097      }
2098      return false;
2099  }
2100  
2101  // Deprecated functions from Moodle 4.0.
2102  
2103  /**
2104   * Generate the URL for starting a new preview of a given question with the given options.
2105   * @param integer $questionid the question to preview.
2106   * @param string $preferredbehaviour the behaviour to use for the preview.
2107   * @param float $maxmark the maximum to mark the question out of.
2108   * @param question_display_options $displayoptions the display options to use.
2109   * @param int $variant the variant of the question to preview. If null, one will
2110   *      be picked randomly.
2111   * @param object $context context to run the preview in (affects things like
2112   *      filter settings, theme, lang, etc.) Defaults to $PAGE->context.
2113   * @return moodle_url the URL.
2114   * @deprecated since Moodle 4.0
2115   * @see qbank_previewquestion\helper::question_preview_url()
2116   * @todo Final deprecation on Moodle 4.4 MDL-72438
2117   */
2118  function question_preview_url($questionid, $preferredbehaviour = null,
2119                                $maxmark = null, $displayoptions = null, $variant = null, $context = null) {
2120      debugging('Function question_preview_url() has been deprecated and moved to qbank_previewquestion plugin,
2121      Please use qbank_previewquestion\previewquestion_helper::question_preview_url() instead.', DEBUG_DEVELOPER);
2122  
2123      return \qbank_previewquestion\helper::question_preview_url($questionid, $preferredbehaviour,
2124          $maxmark, $displayoptions, $variant, $context);
2125  }
2126  
2127  /**
2128   * Popup params for the question preview.
2129   *
2130   * @return array that can be passed as $params to the {@see popup_action()} constructor.
2131   * @deprecated since Moodle 4.0
2132   * @see qbank_previewquestion\previewquestion_helper::question_preview_popup_params()
2133   * @todo Final deprecation on Moodle 4.4 MDL-72438
2134   */
2135  function question_preview_popup_params() {
2136      debugging('Function question_preview_popup_params() has been deprecated and moved to qbank_previewquestion plugin,
2137      Please use qbank_previewquestion\previewquestion_helper::question_preview_popup_params() instead.', DEBUG_DEVELOPER);
2138  
2139      return \qbank_previewquestion\helper::question_preview_popup_params();
2140  }
2141  
2142  /**
2143   * Creates a stamp that uniquely identifies this version of the question
2144   *
2145   * In future we want this to use a hash of the question data to guarantee that
2146   * identical versions have the same version stamp.
2147   *
2148   * @param object $question
2149   * @return string A unique version stamp
2150   * @deprecated since Moodle 4.0
2151   * @todo Final deprecation on Moodle 4.4 MDL-72438
2152   */
2153  function question_hash($question) {
2154      debugging('Function question_hash() has been deprecated without replacement.', DEBUG_DEVELOPER);
2155      return make_unique_id_code();
2156  }
2157  
2158  /**
2159   * Create url for question export.
2160   *
2161   * @param int $contextid
2162   * @param int $categoryid
2163   * @param string $format
2164   * @param string $withcategories
2165   * @param string $withcontexts
2166   * @param string $filename
2167   * @return moodle_url export file url
2168   * @deprecated since Moodle 4.0 MDL-71573
2169   * @see qbank_exportquestions\exportquestions_helper
2170   * @todo Final deprecation on Moodle 4.4 MDL-72438
2171   */
2172  function question_make_export_url($contextid, $categoryid, $format, $withcategories,
2173                                    $withcontexts, $filename) {
2174      debugging('Function question_make_export_url() has been deprecated and moved to qbank_exportquestions plugin,
2175      Please use qbank_exportquestions\exportquestions_helper::question_make_export_url() instead.', DEBUG_DEVELOPER);
2176  
2177      return \qbank_exportquestions\exportquestions_helper::question_make_export_url($contextid, $categoryid, $format,
2178          $withcategories, $withcontexts, $filename);
2179  }
2180  
2181  /**
2182   * Get the URL to export a single question (exportone.php).
2183   *
2184   * @param stdClass|question_definition $question the question definition as obtained from
2185   *      question_bank::load_question_data() or question_bank::make_question().
2186   *      (Only ->id and ->contextid are used.)
2187   * @return moodle_url the requested URL.
2188   * @deprecated since Moodle 4.0
2189   * @see \qbank_exporttoxml\helper::question_get_export_single_question_url()
2190   * @todo Final deprecation on Moodle 4.4 MDL-72438
2191   */
2192  function question_get_export_single_question_url($question) {
2193      debugging('Function question_get_export_single_question_url() has been deprecated and moved to qbank_exporttoxml plugin,
2194       please use qbank_exporttoxml\helper::question_get_export_single_question_url() instead.', DEBUG_DEVELOPER);
2195      qbank_exporttoxml\helper::question_get_export_single_question_url($question);
2196  }
2197  
2198  /**
2199   * Remove stale questions from a category.
2200   *
2201   * While questions should not be left behind when they are not used any more,
2202   * it does happen, maybe via restore, or old logic, or uncovered scenarios. When
2203   * this happens, the users are unable to delete the question category unless
2204   * they move those stale questions to another one category, but to them the
2205   * category is empty as it does not contain anything. The purpose of this function
2206   * is to detect the questions that may have gone stale and remove them.
2207   *
2208   * You will typically use this prior to checking if the category contains questions.
2209   *
2210   * The stale questions (unused and hidden to the user) handled are:
2211   * - hidden questions
2212   * - random questions
2213   *
2214   * @param int $categoryid The category ID.
2215   * @deprecated since Moodle 4.0 MDL-71585
2216   * @see qbank_managecategories\helper
2217   * @todo Final deprecation on Moodle 4.4 MDL-72438
2218   */
2219  function question_remove_stale_questions_from_category($categoryid) {
2220      debugging('Function question_remove_stale_questions_from_category()
2221      has been deprecated and moved to qbank_managecategories plugin,
2222      Please use qbank_managecategories\helper::question_remove_stale_questions_from_category() instead.',
2223          DEBUG_DEVELOPER);
2224      \qbank_managecategories\helper::question_remove_stale_questions_from_category($categoryid);
2225  }
2226  
2227  /**
2228   * Private method, only for the use of add_indented_names().
2229   *
2230   * Recursively adds an indentedname field to each category, starting with the category
2231   * with id $id, and dealing with that category and all its children, and
2232   * return a new array, with those categories in the right order.
2233   *
2234   * @param array $categories an array of categories which has had childids
2235   *          fields added by flatten_category_tree(). Passed by reference for
2236   *          performance only. It is not modfied.
2237   * @param int $id the category to start the indenting process from.
2238   * @param int $depth the indent depth. Used in recursive calls.
2239   * @param int $nochildrenof
2240   * @return array a new array of categories, in the right order for the tree.
2241   * @deprecated since Moodle 4.0 MDL-71585
2242   * @see qbank_managecategories\helper
2243   * @todo Final deprecation on Moodle 4.4 MDL-72438
2244   */
2245  function flatten_category_tree(&$categories, $id, $depth = 0, $nochildrenof = -1) {
2246      debugging('Function flatten_category_tree() has been deprecated and moved to qbank_managecategories plugin,
2247      Please use qbank_managecategories\helper::flatten_category_tree() instead.', DEBUG_DEVELOPER);
2248      return \qbank_managecategories\helper::flatten_category_tree($categories, $id, $depth, $nochildrenof);
2249  }
2250  
2251  /**
2252   * Format categories into an indented list reflecting the tree structure.
2253   *
2254   * @param array $categories An array of category objects, for example from the.
2255   * @param int $nochildrenof
2256   * @return array The formatted list of categories.
2257   * @deprecated since Moodle 4.0 MDL-71585
2258   * @see qbank_managecategories\helper
2259   * @todo Final deprecation on Moodle 4.4 MDL-72438
2260   */
2261  function add_indented_names($categories, $nochildrenof = -1) {
2262      debugging('Function add_indented_names() has been deprecated and moved to qbank_managecategories plugin,
2263      Please use qbank_managecategories\helper::add_indented_names() instead.', DEBUG_DEVELOPER);
2264      return \qbank_managecategories\helper::add_indented_names($categories, $nochildrenof);
2265  }
2266  
2267  /**
2268   * Output a select menu of question categories.
2269   * Categories from this course and (optionally) published categories from other courses
2270   * are included. Optionally, only categories the current user may edit can be included.
2271   *
2272   * @param array $contexts
2273   * @param bool $top
2274   * @param int $currentcat
2275   * @param integer $selected optionally, the id of a category to be selected by
2276   *      default in the dropdown.
2277   * @param int $nochildrenof
2278   * @deprecated since Moodle 4.0 MDL-71585
2279   * @see qbank_managecategories\helper
2280   * @todo Final deprecation on Moodle 4.4 MDL-72438
2281   */
2282  function question_category_select_menu($contexts, $top = false, $currentcat = 0,
2283                                         $selected = "", $nochildrenof = -1) {
2284      debugging('Function question_category_select_menu() has been deprecated and moved to qbank_managecategories plugin,
2285      Please use qbank_managecategories\helper::question_category_select_menu() instead.', DEBUG_DEVELOPER);
2286      \qbank_managecategories\helper::question_category_select_menu($contexts, $top, $currentcat, $selected, $nochildrenof);
2287  }
2288  
2289  /**
2290   * Get all the category objects, including a count of the number of questions in that category,
2291   * for all the categories in the lists $contexts.
2292   *
2293   * @param mixed $contexts either a single contextid, or a comma-separated list of context ids.
2294   * @param string $sortorder used as the ORDER BY clause in the select statement.
2295   * @param bool $top Whether to return the top categories or not.
2296   * @return array of category objects.
2297   * @deprecated since Moodle 4.0 MDL-71585
2298   * @see qbank_managecategories\helper
2299   * @todo Final deprecation on Moodle 4.4 MDL-72438
2300   */
2301  function get_categories_for_contexts($contexts, $sortorder = 'parent, sortorder, name ASC', $top = false) {
2302      debugging('Function get_categories_for_contexts() has been deprecated and moved to qbank_managecategories plugin,
2303      Please use qbank_managecategories\helper::get_categories_for_contexts() instead.', DEBUG_DEVELOPER);
2304      return \qbank_managecategories\helper::get_categories_for_contexts($contexts, $sortorder, $top);
2305  }
2306  
2307  /**
2308   * Output an array of question categories.
2309   *
2310   * @param array $contexts The list of contexts.
2311   * @param bool $top Whether to return the top categories or not.
2312   * @param int $currentcat
2313   * @param bool $popupform
2314   * @param int $nochildrenof
2315   * @param boolean $escapecontextnames Whether the returned name of the thing is to be HTML escaped or not.
2316   * @return array
2317   * @deprecated since Moodle 4.0 MDL-71585
2318   * @see qbank_managecategories\helper
2319   * @todo Final deprecation on Moodle 4.4 MDL-72438
2320   */
2321  function question_category_options($contexts, $top = false, $currentcat = 0,
2322                                     $popupform = false, $nochildrenof = -1, $escapecontextnames = true) {
2323      debugging('Function question_category_options() has been deprecated and moved to qbank_managecategories plugin,
2324      Please use qbank_managecategories\helper::question_category_options() instead.', DEBUG_DEVELOPER);
2325      return \qbank_managecategories\helper::question_category_options($contexts, $top, $currentcat,
2326          $popupform, $nochildrenof, $escapecontextnames);
2327  }
2328  
2329  /**
2330   * Add context in categories key.
2331   *
2332   * @param array $categories The list of categories.
2333   * @return array
2334   * @deprecated since Moodle 4.0 MDL-71585
2335   * @see qbank_managecategories\helper
2336   * @todo Final deprecation on Moodle 4.4 MDL-72438
2337   */
2338  function question_add_context_in_key($categories) {
2339      debugging('Function question_add_context_in_key() has been deprecated and moved to qbank_managecategories plugin,
2340      Please use qbank_managecategories\helper::question_add_context_in_key() instead.', DEBUG_DEVELOPER);
2341      return \qbank_managecategories\helper::question_add_context_in_key($categories);
2342  }
2343  
2344  /**
2345   * Finds top categories in the given categories hierarchy and replace their name with a proper localised string.
2346   *
2347   * @param array $categories An array of question categories.
2348   * @param boolean $escape Whether the returned name of the thing is to be HTML escaped or not.
2349   * @return array The same question category list given to the function, with the top category names being translated.
2350   * @deprecated since Moodle 4.0 MDL-71585
2351   * @see qbank_managecategories\helper
2352   * @todo Final deprecation on Moodle 4.4 MDL-72438
2353   */
2354  function question_fix_top_names($categories, $escape = true) {
2355      debugging('Function question_fix_top_names() has been deprecated and moved to qbank_managecategories plugin,
2356      Please use qbank_managecategories\helper::question_fix_top_names() instead.', DEBUG_DEVELOPER);
2357      return \qbank_managecategories\helper::question_fix_top_names($categories, $escape);
2358  }