Search moodle.org's
Developer Documentation

See Release Notes

  • Bug fixes for general core bugs in 3.11.x will end 14 Nov 2022 (12 months plus 6 months extension).
  • Bug fixes for security issues in 3.11.x will end 13 Nov 2023 (18 months plus 12 months extension).
  • PHP version: minimum PHP 7.3.0 Note: minimum PHP version has increased since Moodle 3.10. PHP 7.4.x is supported too.

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

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