Search moodle.org's
Developer Documentation


  • Bug fixes for general core bugs in 2.8.x ended 9 November 2015 (12 months).
  • Bug fixes for security issues in 2.8.x ended 9 May 2016 (18 months).
  • minimum PHP 5.4.4 (always use latest PHP 5.4.x or 5.5.x on Windows - http://windows.php.net/download/), PHP 7 is NOT supported
  • Differences Between: [Versions 28 and 29] [Versions 28 and 30] [Versions 28 and 31] [Versions 28 and 32] [Versions 28 and 33] [Versions 28 and 34] [Versions 28 and 35] [Versions 28 and 36] [Versions 28 and 37]

       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   * Returns an array of names of activity modules that use this question
     119   *
     120   * @deprecated since Moodle 2.1. Use {@link questions_in_use} instead.
     121   *
     122   * @param object $questionid
     123   * @return array of strings
     124   */
     125  function question_list_instances($questionid) {
     126      throw new coding_exception('question_list_instances has been deprectated. ' .
     127              'Please use questions_in_use instead.');
     128  }
     129  
     130  /**
     131   * @param array $questionids of question ids.
     132   * @return boolean whether any of these questions are being used by any part of Moodle.
     133   */
     134  function questions_in_use($questionids) {
     135      global $CFG;
     136  
     137      if (question_engine::questions_in_use($questionids)) {
     138          return true;
     139      }
     140  
     141      foreach (core_component::get_plugin_list('mod') as $module => $path) {
     142          $lib = $path . '/lib.php';
     143          if (is_readable($lib)) {
     144              include_once($lib);
     145  
     146              $fn = $module . '_questions_in_use';
     147              if (function_exists($fn)) {
     148                  if ($fn($questionids)) {
     149                      return true;
     150                  }
     151              } else {
     152  
     153                  // Fallback for legacy modules.
     154                  $fn = $module . '_question_list_instances';
     155                  if (function_exists($fn)) {
     156                      foreach ($questionids as $questionid) {
     157                          $instances = $fn($questionid);
     158                          if (!empty($instances)) {
     159                              return true;
     160                          }
     161                      }
     162                  }
     163              }
     164          }
     165      }
     166  
     167      return false;
     168  }
     169  
     170  /**
     171   * Determine whether there arey any questions belonging to this context, that is whether any of its
     172   * question categories contain any questions. This will return true even if all the questions are
     173   * hidden.
     174   *
     175   * @param mixed $context either a context object, or a context id.
     176   * @return boolean whether any of the question categories beloning to this context have
     177   *         any questions in them.
     178   */
     179  function question_context_has_any_questions($context) {
     180      global $DB;
     181      if (is_object($context)) {
     182          $contextid = $context->id;
     183      } else if (is_numeric($context)) {
     184          $contextid = $context;
     185      } else {
     186          print_error('invalidcontextinhasanyquestions', 'question');
     187      }
     188      return $DB->record_exists_sql("SELECT *
     189                                       FROM {question} q
     190                                       JOIN {question_categories} qc ON qc.id = q.category
     191                                      WHERE qc.contextid = ? AND q.parent = 0", array($contextid));
     192  }
     193  
     194  /**
     195   * Returns list of 'allowed' grades for grade selection
     196   * formatted suitably for dropdown box function
     197   *
     198   * @deprecated since 2.1. Use {@link question_bank::fraction_options()} or
     199   * {@link question_bank::fraction_options_full()} instead.
     200   *
     201   * @return object ->gradeoptionsfull full array ->gradeoptions +ve only
     202   */
     203  function get_grade_options() {
     204      $grades = new stdClass();
     205      $grades->gradeoptions = question_bank::fraction_options();
     206      $grades->gradeoptionsfull = question_bank::fraction_options_full();
     207  
     208      return $grades;
     209  }
     210  
     211  /**
     212   * Check whether a given grade is one of a list of allowed options. If not,
     213   * depending on $matchgrades, either return the nearest match, or return false
     214   * to signal an error.
     215   * @param array $gradeoptionsfull list of valid options
     216   * @param int $grade grade to be tested
     217   * @param string $matchgrades 'error' or 'nearest'
     218   * @return mixed either 'fixed' value or false if error.
     219   */
     220  function match_grade_options($gradeoptionsfull, $grade, $matchgrades = 'error') {
     221  
     222      if ($matchgrades == 'error') {
     223          // (Almost) exact match, or an error.
     224          foreach ($gradeoptionsfull as $value => $option) {
     225              // Slightly fuzzy test, never check floats for equality.
     226              if (abs($grade - $value) < 0.00001) {
     227                  return $value; // Be sure the return the proper value.
     228              }
     229          }
     230          // Didn't find a match so that's an error.
     231          return false;
     232  
     233      } else if ($matchgrades == 'nearest') {
     234          // Work out nearest value
     235          $best = false;
     236          $bestmismatch = 2;
     237          foreach ($gradeoptionsfull as $value => $option) {
     238              $newmismatch = abs($grade - $value);
     239              if ($newmismatch < $bestmismatch) {
     240                  $best = $value;
     241                  $bestmismatch = $newmismatch;
     242              }
     243          }
     244          return $best;
     245  
     246      } else {
     247          // Unknow option passed.
     248          throw new coding_exception('Unknown $matchgrades ' . $matchgrades .
     249                  ' passed to match_grade_options');
     250      }
     251  }
     252  
     253  /**
     254   * @deprecated Since Moodle 2.1. Use {@link question_category_in_use} instead.
     255   * @param integer $categoryid a question category id.
     256   * @param boolean $recursive whether to check child categories too.
     257   * @return boolean whether any question in this category is in use.
     258   */
     259  function question_category_isused($categoryid, $recursive = false) {
     260      throw new coding_exception('question_category_isused has been deprectated. ' .
     261              'Please use question_category_in_use instead.');
     262  }
     263  
     264  /**
     265   * Category is about to be deleted,
     266   * 1/ All questions are deleted for this question category.
     267   * 2/ Any questions that can't be deleted are moved to a new category
     268   * NOTE: this function is called from lib/db/upgrade.php
     269   *
     270   * @param object|coursecat $category course category object
     271   */
     272  function question_category_delete_safe($category) {
     273      global $DB;
     274      $criteria = array('category' => $category->id);
     275      $context = context::instance_by_id($category->contextid, IGNORE_MISSING);
     276      $rescue = null; // See the code around the call to question_save_from_deletion.
     277  
     278      // Deal with any questions in the category.
     279      if ($questions = $DB->get_records('question', $criteria, '', 'id,qtype')) {
     280  
     281          // Try to delete each question.
     282          foreach ($questions as $question) {
     283              question_delete_question($question->id);
     284          }
     285  
     286          // Check to see if there were any questions that were kept because
     287          // they are still in use somehow, even though quizzes in courses
     288          // in this category will already have been deleted. This could
     289          // happen, for example, if questions are added to a course,
     290          // and then that course is moved to another category (MDL-14802).
     291          $questionids = $DB->get_records_menu('question', $criteria, '', 'id, 1');
     292          if (!empty($questionids)) {
     293              $parentcontextid = SYSCONTEXTID;
     294              $name = get_string('unknown', 'question');
     295              if ($context !== false) {
     296                  $name = $context->get_context_name();
     297                  $parentcontext = $context->get_parent_context();
     298                  if ($parentcontext) {
     299                      $parentcontextid = $parentcontext->id;
     300                  }
     301              }
     302              question_save_from_deletion(array_keys($questionids), $parentcontextid, $name, $rescue);
     303          }
     304      }
     305  
     306      // Now delete the category.
     307      $DB->delete_records('question_categories', array('id' => $category->id));
     308  }
     309  
     310  /**
     311   * Tests whether any question in a category is used by any part of Moodle.
     312   *
     313   * @param integer $categoryid a question category id.
     314   * @param boolean $recursive whether to check child categories too.
     315   * @return boolean whether any question in this category is in use.
     316   */
     317  function question_category_in_use($categoryid, $recursive = false) {
     318      global $DB;
     319  
     320      //Look at each question in the category
     321      if ($questions = $DB->get_records_menu('question',
     322              array('category' => $categoryid), '', 'id, 1')) {
     323          if (questions_in_use(array_keys($questions))) {
     324              return true;
     325          }
     326      }
     327      if (!$recursive) {
     328          return false;
     329      }
     330  
     331      //Look under child categories recursively
     332      if ($children = $DB->get_records('question_categories',
     333              array('parent' => $categoryid), '', 'id, 1')) {
     334          foreach ($children as $child) {
     335              if (question_category_in_use($child->id, $recursive)) {
     336                  return true;
     337              }
     338          }
     339      }
     340  
     341      return false;
     342  }
     343  
     344  /**
     345   * Deletes question and all associated data from the database
     346   *
     347   * It will not delete a question if it is used by an activity module
     348   * @param object $question  The question being deleted
     349   */
     350  function question_delete_question($questionid) {
     351      global $DB;
     352  
     353      $question = $DB->get_record_sql('
     354              SELECT q.*, qc.contextid
     355              FROM {question} q
     356              JOIN {question_categories} qc ON qc.id = q.category
     357              WHERE q.id = ?', array($questionid));
     358      if (!$question) {
     359          // In some situations, for example if this was a child of a
     360          // Cloze question that was previously deleted, the question may already
     361          // have gone. In this case, just do nothing.
     362          return;
     363      }
     364  
     365      // Do not delete a question if it is used by an activity module
     366      if (questions_in_use(array($questionid))) {
     367          return;
     368      }
     369  
     370      $dm = new question_engine_data_mapper();
     371      $dm->delete_previews($questionid);
     372  
     373      // delete questiontype-specific data
     374      question_bank::get_qtype($question->qtype, false)->delete_question(
     375              $questionid, $question->contextid);
     376  
     377      // Delete all tag instances.
     378      $DB->delete_records('tag_instance', array('component' => 'core_question', 'itemid' => $question->id));
     379  
     380      // Now recursively delete all child questions
     381      if ($children = $DB->get_records('question',
     382              array('parent' => $questionid), '', 'id, qtype')) {
     383          foreach ($children as $child) {
     384              if ($child->id != $questionid) {
     385                  question_delete_question($child->id);
     386              }
     387          }
     388      }
     389  
     390      // Finally delete the question record itself
     391      $DB->delete_records('question', array('id' => $questionid));
     392      question_bank::notify_question_edited($questionid);
     393  }
     394  
     395  /**
     396   * All question categories and their questions are deleted for this context id.
     397   *
     398   * @param object $contextid The contextid to delete question categories from
     399   * @return array Feedback from deletes (if any)
     400   */
     401  function question_delete_context($contextid) {
     402      global $DB;
     403  
     404      //To store feedback to be showed at the end of the process
     405      $feedbackdata   = array();
     406  
     407      //Cache some strings
     408      $strcatdeleted = get_string('unusedcategorydeleted', 'question');
     409      $fields = 'id, parent, name, contextid';
     410      if ($categories = $DB->get_records('question_categories', array('contextid' => $contextid), 'parent', $fields)) {
     411          //Sort categories following their tree (parent-child) relationships
     412          //this will make the feedback more readable
     413          $categories = sort_categories_by_tree($categories);
     414  
     415          foreach ($categories as $category) {
     416              question_category_delete_safe($category);
     417  
     418              //Fill feedback
     419              $feedbackdata[] = array($category->name, $strcatdeleted);
     420          }
     421      }
     422      return $feedbackdata;
     423  }
     424  
     425  /**
     426   * All question categories and their questions are deleted for this course.
     427   *
     428   * @param stdClass $course an object representing the activity
     429   * @param boolean $feedback to specify if the process must output a summary of its work
     430   * @return boolean
     431   */
     432  function question_delete_course($course, $feedback=true) {
     433      $coursecontext = context_course::instance($course->id);
     434      $feedbackdata = question_delete_context($coursecontext->id, $feedback);
     435  
     436      // Inform about changes performed if feedback is enabled.
     437      if ($feedback && $feedbackdata) {
     438          $table = new html_table();
     439          $table->head = array(get_string('category', 'question'), get_string('action'));
     440          $table->data = $feedbackdata;
     441          echo html_writer::table($table);
     442      }
     443      return true;
     444  }
     445  
     446  /**
     447   * Category is about to be deleted,
     448   * 1/ All question categories and their questions are deleted for this course category.
     449   * 2/ All questions are moved to new category
     450   *
     451   * @param object|coursecat $category course category object
     452   * @param object|coursecat $newcategory empty means everything deleted, otherwise id of
     453   *      category where content moved
     454   * @param boolean $feedback to specify if the process must output a summary of its work
     455   * @return boolean
     456   */
     457  function question_delete_course_category($category, $newcategory, $feedback=true) {
     458      global $DB, $OUTPUT;
     459  
     460      $context = context_coursecat::instance($category->id);
     461      if (empty($newcategory)) {
     462          $feedbackdata = question_delete_context($context->id, $feedback);
     463  
     464          // Output feedback if requested.
     465          if ($feedback && $feedbackdata) {
     466              $table = new html_table();
     467              $table->head = array(get_string('questioncategory', 'question'), get_string('action'));
     468              $table->data = $feedbackdata;
     469              echo html_writer::table($table);
     470          }
     471  
     472      } else {
     473          // Move question categories to the new context.
     474          if (!$newcontext = context_coursecat::instance($newcategory->id)) {
     475              return false;
     476          }
     477  
     478          // Update the contextid for any tag instances for questions in the old context.
     479          $DB->set_field('tag_instance', 'contextid', $newcontext->id, array('component' => 'core_question',
     480              'contextid' => $context->id));
     481  
     482          $DB->set_field('question_categories', 'contextid', $newcontext->id, array('contextid' => $context->id));
     483  
     484          if ($feedback) {
     485              $a = new stdClass();
     486              $a->oldplace = $context->get_context_name();
     487              $a->newplace = $newcontext->get_context_name();
     488              echo $OUTPUT->notification(
     489                      get_string('movedquestionsandcategories', 'question', $a), 'notifysuccess');
     490          }
     491      }
     492  
     493      return true;
     494  }
     495  
     496  /**
     497   * Enter description here...
     498   *
     499   * @param array $questionids of question ids
     500   * @param object $newcontextid the context to create the saved category in.
     501   * @param string $oldplace a textual description of the think being deleted,
     502   *      e.g. from get_context_name
     503   * @param object $newcategory
     504   * @return mixed false on
     505   */
     506  function question_save_from_deletion($questionids, $newcontextid, $oldplace,
     507          $newcategory = null) {
     508      global $DB;
     509  
     510      // Make a category in the parent context to move the questions to.
     511      if (is_null($newcategory)) {
     512          $newcategory = new stdClass();
     513          $newcategory->parent = 0;
     514          $newcategory->contextid = $newcontextid;
     515          $newcategory->name = get_string('questionsrescuedfrom', 'question', $oldplace);
     516          $newcategory->info = get_string('questionsrescuedfrominfo', 'question', $oldplace);
     517          $newcategory->sortorder = 999;
     518          $newcategory->stamp = make_unique_id_code();
     519          $newcategory->id = $DB->insert_record('question_categories', $newcategory);
     520      }
     521  
     522      // Move any remaining questions to the 'saved' category.
     523      if (!question_move_questions_to_category($questionids, $newcategory->id)) {
     524          return false;
     525      }
     526      return $newcategory;
     527  }
     528  
     529  /**
     530   * All question categories and their questions are deleted for this activity.
     531   *
     532   * @param object $cm the course module object representing the activity
     533   * @param boolean $feedback to specify if the process must output a summary of its work
     534   * @return boolean
     535   */
     536  function question_delete_activity($cm, $feedback=true) {
     537      global $DB;
     538  
     539      $modcontext = context_module::instance($cm->id);
     540      $feedbackdata = question_delete_context($modcontext->id, $feedback);
     541      // Inform about changes performed if feedback is enabled.
     542      if ($feedback && $feedbackdata) {
     543          $table = new html_table();
     544          $table->head = array(get_string('category', 'question'), get_string('action'));
     545          $table->data = $feedbackdata;
     546          echo html_writer::table($table);
     547      }
     548      return true;
     549  }
     550  
     551  /**
     552   * This function should be considered private to the question bank, it is called from
     553   * question/editlib.php question/contextmoveq.php and a few similar places to to the
     554   * work of acutally moving questions and associated data. However, callers of this
     555   * function also have to do other work, which is why you should not call this method
     556   * directly from outside the questionbank.
     557   *
     558   * @param array $questionids of question ids.
     559   * @param integer $newcategoryid the id of the category to move to.
     560   */
     561  function question_move_questions_to_category($questionids, $newcategoryid) {
     562      global $DB;
     563  
     564      $newcontextid = $DB->get_field('question_categories', 'contextid',
     565              array('id' => $newcategoryid));
     566      list($questionidcondition, $params) = $DB->get_in_or_equal($questionids);
     567      $questions = $DB->get_records_sql("
     568              SELECT q.id, q.qtype, qc.contextid
     569                FROM {question} q
     570                JOIN {question_categories} qc ON q.category = qc.id
     571               WHERE  q.id $questionidcondition", $params);
     572      foreach ($questions as $question) {
     573          if ($newcontextid != $question->contextid) {
     574              question_bank::get_qtype($question->qtype)->move_files(
     575                      $question->id, $question->contextid, $newcontextid);
     576          }
     577      }
     578  
     579      // Move the questions themselves.
     580      $DB->set_field_select('question', 'category', $newcategoryid,
     581              "id $questionidcondition", $params);
     582  
     583      // Move any subquestions belonging to them.
     584      $DB->set_field_select('question', 'category', $newcategoryid,
     585              "parent $questionidcondition", $params);
     586  
     587      // Update the contextid for any tag instances that may exist for these questions.
     588      $DB->set_field_select('tag_instance', 'contextid', $newcontextid,
     589          "component = 'core_question' AND itemid $questionidcondition", $params);
     590  
     591      // TODO Deal with datasets.
     592  
     593      // Purge these questions from the cache.
     594      foreach ($questions as $question) {
     595          question_bank::notify_question_edited($question->id);
     596      }
     597  
     598      return true;
     599  }
     600  
     601  /**
     602   * This function helps move a question cateogry to a new context by moving all
     603   * the files belonging to all the questions to the new context.
     604   * Also moves subcategories.
     605   * @param integer $categoryid the id of the category being moved.
     606   * @param integer $oldcontextid the old context id.
     607   * @param integer $newcontextid the new context id.
     608   */
     609  function question_move_category_to_context($categoryid, $oldcontextid, $newcontextid) {
     610      global $DB;
     611  
     612      $questionids = $DB->get_records_menu('question',
     613              array('category' => $categoryid), '', 'id,qtype');
     614      foreach ($questionids as $questionid => $qtype) {
     615          question_bank::get_qtype($qtype)->move_files(
     616                  $questionid, $oldcontextid, $newcontextid);
     617          // Purge this question from the cache.
     618          question_bank::notify_question_edited($questionid);
     619      }
     620  
     621      if ($questionids) {
     622          // Update the contextid for any tag instances that may exist for these questions.
     623          list($questionids, $params) = $DB->get_in_or_equal(array_keys($questionids));
     624          $DB->set_field_select('tag_instance', 'contextid', $newcontextid,
     625              "component = 'core_question' AND itemid $questionids", $params);
     626      }
     627  
     628      $subcatids = $DB->get_records_menu('question_categories',
     629              array('parent' => $categoryid), '', 'id,1');
     630      foreach ($subcatids as $subcatid => $notused) {
     631          $DB->set_field('question_categories', 'contextid', $newcontextid,
     632                  array('id' => $subcatid));
     633          question_move_category_to_context($subcatid, $oldcontextid, $newcontextid);
     634      }
     635  }
     636  
     637  /**
     638   * Generate the URL for starting a new preview of a given question with the given options.
     639   * @param integer $questionid the question to preview.
     640   * @param string $preferredbehaviour the behaviour to use for the preview.
     641   * @param float $maxmark the maximum to mark the question out of.
     642   * @param question_display_options $displayoptions the display options to use.
     643   * @param int $variant the variant of the question to preview. If null, one will
     644   *      be picked randomly.
     645   * @param object $context context to run the preview in (affects things like
     646   *      filter settings, theme, lang, etc.) Defaults to $PAGE->context.
     647   * @return moodle_url the URL.
     648   */
     649  function question_preview_url($questionid, $preferredbehaviour = null,
     650          $maxmark = null, $displayoptions = null, $variant = null, $context = null) {
     651  
     652      $params = array('id' => $questionid);
     653  
     654      if (is_null($context)) {
     655          global $PAGE;
     656          $context = $PAGE->context;
     657      }
     658      if ($context->contextlevel == CONTEXT_MODULE) {
     659          $params['cmid'] = $context->instanceid;
     660      } else if ($context->contextlevel == CONTEXT_COURSE) {
     661          $params['courseid'] = $context->instanceid;
     662      }
     663  
     664      if (!is_null($preferredbehaviour)) {
     665          $params['behaviour'] = $preferredbehaviour;
     666      }
     667  
     668      if (!is_null($maxmark)) {
     669          $params['maxmark'] = $maxmark;
     670      }
     671  
     672      if (!is_null($displayoptions)) {
     673          $params['correctness']     = $displayoptions->correctness;
     674          $params['marks']           = $displayoptions->marks;
     675          $params['markdp']          = $displayoptions->markdp;
     676          $params['feedback']        = (bool) $displayoptions->feedback;
     677          $params['generalfeedback'] = (bool) $displayoptions->generalfeedback;
     678          $params['rightanswer']     = (bool) $displayoptions->rightanswer;
     679          $params['history']         = (bool) $displayoptions->history;
     680      }
     681  
     682      if ($variant) {
     683          $params['variant'] = $variant;
     684      }
     685  
     686      return new moodle_url('/question/preview.php', $params);
     687  }
     688  
     689  /**
     690   * @return array that can be passed as $params to the {@link popup_action} constructor.
     691   */
     692  function question_preview_popup_params() {
     693      return array(
     694          'height' => 600,
     695          'width' => 800,
     696      );
     697  }
     698  
     699  /**
     700   * Given a list of ids, load the basic information about a set of questions from
     701   * the questions table. The $join and $extrafields arguments can be used together
     702   * to pull in extra data. See, for example, the usage in mod/quiz/attemptlib.php, and
     703   * read the code below to see how the SQL is assembled. Throws exceptions on error.
     704   *
     705   * @param array $questionids array of question ids to load. If null, then all
     706   * questions matched by $join will be loaded.
     707   * @param string $extrafields extra SQL code to be added to the query.
     708   * @param string $join extra SQL code to be added to the query.
     709   * @param array $extraparams values for any placeholders in $join.
     710   * You must use named placeholders.
     711   * @param string $orderby what to order the results by. Optional, default is unspecified order.
     712   *
     713   * @return array partially complete question objects. You need to call get_question_options
     714   * on them before they can be properly used.
     715   */
     716  function question_preload_questions($questionids = null, $extrafields = '', $join = '',
     717          $extraparams = array(), $orderby = '') {
     718      global $DB;
     719  
     720      if ($questionids === null) {
     721          $where = '';
     722          $params = array();
     723      } else {
     724          if (empty($questionids)) {
     725              return array();
     726          }
     727  
     728          list($questionidcondition, $params) = $DB->get_in_or_equal(
     729                  $questionids, SQL_PARAMS_NAMED, 'qid0000');
     730          $where = 'WHERE q.id ' . $questionidcondition;
     731      }
     732  
     733      if ($join) {
     734          $join = 'JOIN ' . $join;
     735      }
     736  
     737      if ($extrafields) {
     738          $extrafields = ', ' . $extrafields;
     739      }
     740  
     741      if ($orderby) {
     742          $orderby = 'ORDER BY ' . $orderby;
     743      }
     744  
     745      $sql = "SELECT q.*, qc.contextid{$extrafields}
     746                FROM {question} q
     747                JOIN {question_categories} qc ON q.category = qc.id
     748                {$join}
     749               {$where}
     750            {$orderby}";
     751  
     752      // Load the questions.
     753      $questions = $DB->get_records_sql($sql, $extraparams + $params);
     754      foreach ($questions as $question) {
     755          $question->_partiallyloaded = true;
     756      }
     757  
     758      return $questions;
     759  }
     760  
     761  /**
     762   * Load a set of questions, given a list of ids. The $join and $extrafields arguments can be used
     763   * together to pull in extra data. See, for example, the usage in mod/quiz/attempt.php, and
     764   * read the code below to see how the SQL is assembled. Throws exceptions on error.
     765   *
     766   * @param array $questionids array of question ids.
     767   * @param string $extrafields extra SQL code to be added to the query.
     768   * @param string $join extra SQL code to be added to the query.
     769   * @param array $extraparams values for any placeholders in $join.
     770   * You are strongly recommended to use named placeholder.
     771   *
     772   * @return array question objects.
     773   */
     774  function question_load_questions($questionids, $extrafields = '', $join = '') {
     775      $questions = question_preload_questions($questionids, $extrafields, $join);
     776  
     777      // Load the question type specific information
     778      if (!get_question_options($questions)) {
     779          return 'Could not load the question options';
     780      }
     781  
     782      return $questions;
     783  }
     784  
     785  /**
     786   * Private function to factor common code out of get_question_options().
     787   *
     788   * @param object $question the question to tidy.
     789   * @param boolean $loadtags load the question tags from the tags table. Optional, default false.
     790   */
     791  function _tidy_question($question, $loadtags = false) {
     792      global $CFG;
     793  
     794      // Load question-type specific fields.
     795      if (!question_bank::is_qtype_installed($question->qtype)) {
     796          $question->questiontext = html_writer::tag('p', get_string('warningmissingtype',
     797                  'qtype_missingtype')) . $question->questiontext;
     798      }
     799      question_bank::get_qtype($question->qtype)->get_question_options($question);
     800  
     801      // Convert numeric fields to float. (Prevents these being displayed as 1.0000000.)
     802      $question->defaultmark += 0;
     803      $question->penalty += 0;
     804  
     805      if (isset($question->_partiallyloaded)) {
     806          unset($question->_partiallyloaded);
     807      }
     808  
     809      if ($loadtags && !empty($CFG->usetags)) {
     810          require_once($CFG->dirroot . '/tag/lib.php');
     811          $question->tags = tag_get_tags_array('question', $question->id);
     812      }
     813  }
     814  
     815  /**
     816   * Updates the question objects with question type specific
     817   * information by calling {@link get_question_options()}
     818   *
     819   * Can be called either with an array of question objects or with a single
     820   * question object.
     821   *
     822   * @param mixed $questions Either an array of question objects to be updated
     823   *         or just a single question object
     824   * @param boolean $loadtags load the question tags from the tags table. Optional, default false.
     825   * @return bool Indicates success or failure.
     826   */
     827  function get_question_options(&$questions, $loadtags = false) {
     828      if (is_array($questions)) { // deal with an array of questions
     829          foreach ($questions as $i => $notused) {
     830              _tidy_question($questions[$i], $loadtags);
     831          }
     832      } else { // deal with single question
     833          _tidy_question($questions, $loadtags);
     834      }
     835      return true;
     836  }
     837  
     838  /**
     839   * Print the icon for the question type
     840   *
     841   * @param object $question The question object for which the icon is required.
     842   *       Only $question->qtype is used.
     843   * @return string the HTML for the img tag.
     844   */
     845  function print_question_icon($question) {
     846      global $PAGE;
     847      return $PAGE->get_renderer('question', 'bank')->qtype_icon($question->qtype);
     848  }
     849  
     850  /**
     851   * Creates a stamp that uniquely identifies this version of the question
     852   *
     853   * In future we want this to use a hash of the question data to guarantee that
     854   * identical versions have the same version stamp.
     855   *
     856   * @param object $question
     857   * @return string A unique version stamp
     858   */
     859  function question_hash($question) {
     860      return make_unique_id_code();
     861  }
     862  
     863  /// FUNCTIONS THAT SIMPLY WRAP QUESTIONTYPE METHODS //////////////////////////////////
     864  /**
     865   * Saves question options
     866   *
     867   * Simply calls the question type specific save_question_options() method.
     868   * @deprecated all code should now call the question type method directly.
     869   */
     870  function save_question_options($question) {
     871      debugging('Please do not call save_question_options any more. Call the question type method directly.',
     872              DEBUG_DEVELOPER);
     873      question_bank::get_qtype($question->qtype)->save_question_options($question);
     874  }
     875  
     876  /// CATEGORY FUNCTIONS /////////////////////////////////////////////////////////////////
     877  
     878  /**
     879   * returns the categories with their names ordered following parent-child relationships
     880   * finally it tries to return pending categories (those being orphaned, whose parent is
     881   * incorrect) to avoid missing any category from original array.
     882   */
     883  function sort_categories_by_tree(&$categories, $id = 0, $level = 1) {
     884      global $DB;
     885  
     886      $children = array();
     887      $keys = array_keys($categories);
     888  
     889      foreach ($keys as $key) {
     890          if (!isset($categories[$key]->processed) && $categories[$key]->parent == $id) {
     891              $children[$key] = $categories[$key];
     892              $categories[$key]->processed = true;
     893              $children = $children + sort_categories_by_tree(
     894                      $categories, $children[$key]->id, $level+1);
     895          }
     896      }
     897      //If level = 1, we have finished, try to look for non processed categories
     898      // (bad parent) and sort them too
     899      if ($level == 1) {
     900          foreach ($keys as $key) {
     901              // If not processed and it's a good candidate to start (because its
     902              // parent doesn't exist in the course)
     903              if (!isset($categories[$key]->processed) && !$DB->record_exists('question_categories',
     904                      array('contextid' => $categories[$key]->contextid,
     905                              'id' => $categories[$key]->parent))) {
     906                  $children[$key] = $categories[$key];
     907                  $categories[$key]->processed = true;
     908                  $children = $children + sort_categories_by_tree(
     909                          $categories, $children[$key]->id, $level + 1);
     910              }
     911          }
     912      }
     913      return $children;
     914  }
     915  
     916  /**
     917   * Private method, only for the use of add_indented_names().
     918   *
     919   * Recursively adds an indentedname field to each category, starting with the category
     920   * with id $id, and dealing with that category and all its children, and
     921   * return a new array, with those categories in the right order.
     922   *
     923   * @param array $categories an array of categories which has had childids
     924   *          fields added by flatten_category_tree(). Passed by reference for
     925   *          performance only. It is not modfied.
     926   * @param int $id the category to start the indenting process from.
     927   * @param int $depth the indent depth. Used in recursive calls.
     928   * @return array a new array of categories, in the right order for the tree.
     929   */
     930  function flatten_category_tree(&$categories, $id, $depth = 0, $nochildrenof = -1) {
     931  
     932      // Indent the name of this category.
     933      $newcategories = array();
     934      $newcategories[$id] = $categories[$id];
     935      $newcategories[$id]->indentedname = str_repeat('&nbsp;&nbsp;&nbsp;', $depth) .
     936              $categories[$id]->name;
     937  
     938      // Recursively indent the children.
     939      foreach ($categories[$id]->childids as $childid) {
     940          if ($childid != $nochildrenof) {
     941              $newcategories = $newcategories + flatten_category_tree(
     942                      $categories, $childid, $depth + 1, $nochildrenof);
     943          }
     944      }
     945  
     946      // Remove the childids array that were temporarily added.
     947      unset($newcategories[$id]->childids);
     948  
     949      return $newcategories;
     950  }
     951  
     952  /**
     953   * Format categories into an indented list reflecting the tree structure.
     954   *
     955   * @param array $categories An array of category objects, for example from the.
     956   * @return array The formatted list of categories.
     957   */
     958  function add_indented_names($categories, $nochildrenof = -1) {
     959  
     960      // Add an array to each category to hold the child category ids. This array
     961      // will be removed again by flatten_category_tree(). It should not be used
     962      // outside these two functions.
     963      foreach (array_keys($categories) as $id) {
     964          $categories[$id]->childids = array();
     965      }
     966  
     967      // Build the tree structure, and record which categories are top-level.
     968      // We have to be careful, because the categories array may include published
     969      // categories from other courses, but not their parents.
     970      $toplevelcategoryids = array();
     971      foreach (array_keys($categories) as $id) {
     972          if (!empty($categories[$id]->parent) &&
     973                  array_key_exists($categories[$id]->parent, $categories)) {
     974              $categories[$categories[$id]->parent]->childids[] = $id;
     975          } else {
     976              $toplevelcategoryids[] = $id;
     977          }
     978      }
     979  
     980      // Flatten the tree to and add the indents.
     981      $newcategories = array();
     982      foreach ($toplevelcategoryids as $id) {
     983          $newcategories = $newcategories + flatten_category_tree(
     984                  $categories, $id, 0, $nochildrenof);
     985      }
     986  
     987      return $newcategories;
     988  }
     989  
     990  /**
     991   * Output a select menu of question categories.
     992   *
     993   * Categories from this course and (optionally) published categories from other courses
     994   * are included. Optionally, only categories the current user may edit can be included.
     995   *
     996   * @param integer $courseid the id of the course to get the categories for.
     997   * @param integer $published if true, include publised categories from other courses.
     998   * @param integer $only_editable if true, exclude categories this user is not allowed to edit.
     999   * @param integer $selected optionally, the id of a category to be selected by
    1000   *      default in the dropdown.
    1001   */
    1002  function question_category_select_menu($contexts, $top = false, $currentcat = 0,
    1003          $selected = "", $nochildrenof = -1) {
    1004      global $OUTPUT;
    1005      $categoriesarray = question_category_options($contexts, $top, $currentcat,
    1006              false, $nochildrenof);
    1007      if ($selected) {
    1008          $choose = '';
    1009      } else {
    1010          $choose = 'choosedots';
    1011      }
    1012      $options = array();
    1013      foreach ($categoriesarray as $group => $opts) {
    1014          $options[] = array($group => $opts);
    1015      }
    1016      echo html_writer::label(get_string('questioncategory', 'core_question'), 'id_movetocategory', false, array('class' => 'accesshide'));
    1017      echo html_writer::select($options, 'category', $selected, $choose, array('id' => 'id_movetocategory'));
    1018  }
    1019  
    1020  /**
    1021   * @param integer $contextid a context id.
    1022   * @return object the default question category for that context, or false if none.
    1023   */
    1024  function question_get_default_category($contextid) {
    1025      global $DB;
    1026      $category = $DB->get_records('question_categories',
    1027              array('contextid' => $contextid), 'id', '*', 0, 1);
    1028      if (!empty($category)) {
    1029          return reset($category);
    1030      } else {
    1031          return false;
    1032      }
    1033  }
    1034  
    1035  /**
    1036   * Gets the default category in the most specific context.
    1037   * If no categories exist yet then default ones are created in all contexts.
    1038   *
    1039   * @param array $contexts  The context objects for this context and all parent contexts.
    1040   * @return object The default category - the category in the course context
    1041   */
    1042  function question_make_default_categories($contexts) {
    1043      global $DB;
    1044      static $preferredlevels = array(
    1045          CONTEXT_COURSE => 4,
    1046          CONTEXT_MODULE => 3,
    1047          CONTEXT_COURSECAT => 2,
    1048          CONTEXT_SYSTEM => 1,
    1049      );
    1050  
    1051      $toreturn = null;
    1052      $preferredness = 0;
    1053      // If it already exists, just return it.
    1054      foreach ($contexts as $key => $context) {
    1055          if (!$exists = $DB->record_exists("question_categories",
    1056                  array('contextid' => $context->id))) {
    1057              // Otherwise, we need to make one
    1058              $category = new stdClass();
    1059              $contextname = $context->get_context_name(false, true);
    1060              $category->name = get_string('defaultfor', 'question', $contextname);
    1061              $category->info = get_string('defaultinfofor', 'question', $contextname);
    1062              $category->contextid = $context->id;
    1063              $category->parent = 0;
    1064              // By default, all categories get this number, and are sorted alphabetically.
    1065              $category->sortorder = 999;
    1066              $category->stamp = make_unique_id_code();
    1067              $category->id = $DB->insert_record('question_categories', $category);
    1068          } else {
    1069              $category = question_get_default_category($context->id);
    1070          }
    1071          $thispreferredness = $preferredlevels[$context->contextlevel];
    1072          if (has_any_capability(array('moodle/question:usemine', 'moodle/question:useall'), $context)) {
    1073              $thispreferredness += 10;
    1074          }
    1075          if ($thispreferredness > $preferredness) {
    1076              $toreturn = $category;
    1077              $preferredness = $thispreferredness;
    1078          }
    1079      }
    1080  
    1081      if (!is_null($toreturn)) {
    1082          $toreturn = clone($toreturn);
    1083      }
    1084      return $toreturn;
    1085  }
    1086  
    1087  /**
    1088   * Get all the category objects, including a count of the number of questions in that category,
    1089   * for all the categories in the lists $contexts.
    1090   *
    1091   * @param mixed $contexts either a single contextid, or a comma-separated list of context ids.
    1092   * @param string $sortorder used as the ORDER BY clause in the select statement.
    1093   * @return array of category objects.
    1094   */
    1095  function get_categories_for_contexts($contexts, $sortorder = 'parent, sortorder, name ASC') {
    1096      global $DB;
    1097      return $DB->get_records_sql("
    1098              SELECT c.*, (SELECT count(1) FROM {question} q
    1099                          WHERE c.id = q.category AND q.hidden='0' AND q.parent='0') AS questioncount
    1100                FROM {question_categories} c
    1101               WHERE c.contextid IN ($contexts)
    1102            ORDER BY $sortorder");
    1103  }
    1104  
    1105  /**
    1106   * Output an array of question categories.
    1107   */
    1108  function question_category_options($contexts, $top = false, $currentcat = 0,
    1109          $popupform = false, $nochildrenof = -1) {
    1110      global $CFG;
    1111      $pcontexts = array();
    1112      foreach ($contexts as $context) {
    1113          $pcontexts[] = $context->id;
    1114      }
    1115      $contextslist = join($pcontexts, ', ');
    1116  
    1117      $categories = get_categories_for_contexts($contextslist);
    1118  
    1119      $categories = question_add_context_in_key($categories);
    1120  
    1121      if ($top) {
    1122          $categories = question_add_tops($categories, $pcontexts);
    1123      }
    1124      $categories = add_indented_names($categories, $nochildrenof);
    1125  
    1126      // sort cats out into different contexts
    1127      $categoriesarray = array();
    1128      foreach ($pcontexts as $contextid) {
    1129          $context = context::instance_by_id($contextid);
    1130          $contextstring = $context->get_context_name(true, true);
    1131          foreach ($categories as $category) {
    1132              if ($category->contextid == $contextid) {
    1133                  $cid = $category->id;
    1134                  if ($currentcat != $cid || $currentcat == 0) {
    1135                      $countstring = !empty($category->questioncount) ?
    1136                              " ($category->questioncount)" : '';
    1137                      $categoriesarray[$contextstring][$cid] =
    1138                              format_string($category->indentedname, true,
    1139                                  array('context' => $context)) . $countstring;
    1140                  }
    1141              }
    1142          }
    1143      }
    1144      if ($popupform) {
    1145          $popupcats = array();
    1146          foreach ($categoriesarray as $contextstring => $optgroup) {
    1147              $group = array();
    1148              foreach ($optgroup as $key => $value) {
    1149                  $key = str_replace($CFG->wwwroot, '', $key);
    1150                  $group[$key] = $value;
    1151              }
    1152              $popupcats[] = array($contextstring => $group);
    1153          }
    1154          return $popupcats;
    1155      } else {
    1156          return $categoriesarray;
    1157      }
    1158  }
    1159  
    1160  function question_add_context_in_key($categories) {
    1161      $newcatarray = array();
    1162      foreach ($categories as $id => $category) {
    1163          $category->parent = "$category->parent,$category->contextid";
    1164          $category->id = "$category->id,$category->contextid";
    1165          $newcatarray["$id,$category->contextid"] = $category;
    1166      }
    1167      return $newcatarray;
    1168  }
    1169  
    1170  function question_add_tops($categories, $pcontexts) {
    1171      $topcats = array();
    1172      foreach ($pcontexts as $context) {
    1173          $newcat = new stdClass();
    1174          $newcat->id = "0,$context";
    1175          $newcat->name = get_string('top');
    1176          $newcat->parent = -1;
    1177          $newcat->contextid = $context;
    1178          $topcats["0,$context"] = $newcat;
    1179      }
    1180      //put topcats in at beginning of array - they'll be sorted into different contexts later.
    1181      return array_merge($topcats, $categories);
    1182  }
    1183  
    1184  /**
    1185   * @return array of question category ids of the category and all subcategories.
    1186   */
    1187  function question_categorylist($categoryid) {
    1188      global $DB;
    1189  
    1190      // final list of category IDs
    1191      $categorylist = array();
    1192  
    1193      // a list of category IDs to check for any sub-categories
    1194      $subcategories = array($categoryid);
    1195  
    1196      while ($subcategories) {
    1197          foreach ($subcategories as $subcategory) {
    1198              // if anything from the temporary list was added already, then we have a loop
    1199              if (isset($categorylist[$subcategory])) {
    1200                  throw new coding_exception("Category id=$subcategory is already on the list - loop of categories detected.");
    1201              }
    1202              $categorylist[$subcategory] = $subcategory;
    1203          }
    1204  
    1205          list ($in, $params) = $DB->get_in_or_equal($subcategories);
    1206  
    1207          $subcategories = $DB->get_records_select_menu('question_categories',
    1208                  "parent $in", $params, NULL, 'id,id AS id2');
    1209      }
    1210  
    1211      return $categorylist;
    1212  }
    1213  
    1214  //===========================
    1215  // Import/Export Functions
    1216  //===========================
    1217  
    1218  /**
    1219   * Get list of available import or export formats
    1220   * @param string $type 'import' if import list, otherwise export list assumed
    1221   * @return array sorted list of import/export formats available
    1222   */
    1223  function get_import_export_formats($type) {
    1224      global $CFG;
    1225      require_once($CFG->dirroot . '/question/format.php');
    1226  
    1227      $formatclasses = core_component::get_plugin_list_with_class('qformat', '', 'format.php');
    1228  
    1229      $fileformatname = array();
    1230      foreach ($formatclasses as $component => $formatclass) {
    1231  
    1232          $format = new $formatclass();
    1233          if ($type == 'import') {
    1234              $provided = $format->provide_import();
    1235          } else {
    1236              $provided = $format->provide_export();
    1237          }
    1238  
    1239          if ($provided) {
    1240              list($notused, $fileformat) = explode('_', $component, 2);
    1241              $fileformatnames[$fileformat] = get_string('pluginname', $component);
    1242          }
    1243      }
    1244  
    1245      core_collator::asort($fileformatnames);
    1246      return $fileformatnames;
    1247  }
    1248  
    1249  
    1250  /**
    1251   * Create a reasonable default file name for exporting questions from a particular
    1252   * category.
    1253   * @param object $course the course the questions are in.
    1254   * @param object $category the question category.
    1255   * @return string the filename.
    1256   */
    1257  function question_default_export_filename($course, $category) {
    1258      // We build a string that is an appropriate name (questions) from the lang pack,
    1259      // then the corse shortname, then the question category name, then a timestamp.
    1260  
    1261      $base = clean_filename(get_string('exportfilename', 'question'));
    1262  
    1263      $dateformat = str_replace(' ', '_', get_string('exportnameformat', 'question'));
    1264      $timestamp = clean_filename(userdate(time(), $dateformat, 99, false));
    1265  
    1266      $shortname = clean_filename($course->shortname);
    1267      if ($shortname == '' || $shortname == '_' ) {
    1268          $shortname = $course->id;
    1269      }
    1270  
    1271      $categoryname = clean_filename(format_string($category->name));
    1272  
    1273      return "{$base}-{$shortname}-{$categoryname}-{$timestamp}";
    1274  
    1275      return $export_name;
    1276  }
    1277  
    1278  /**
    1279   * Converts contextlevels to strings and back to help with reading/writing contexts
    1280   * to/from import/export files.
    1281   *
    1282   * @copyright 1999 onwards Martin Dougiamas  {@link http://moodle.com}
    1283   * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
    1284   */
    1285  class context_to_string_translator{
    1286      /**
    1287       * @var array used to translate between contextids and strings for this context.
    1288       */
    1289      protected $contexttostringarray = array();
    1290  
    1291      public function __construct($contexts) {
    1292          $this->generate_context_to_string_array($contexts);
    1293      }
    1294  
    1295      public function context_to_string($contextid) {
    1296          return $this->contexttostringarray[$contextid];
    1297      }
    1298  
    1299      public function string_to_context($contextname) {
    1300          $contextid = array_search($contextname, $this->contexttostringarray);
    1301          return $contextid;
    1302      }
    1303  
    1304      protected function generate_context_to_string_array($contexts) {
    1305          if (!$this->contexttostringarray) {
    1306              $catno = 1;
    1307              foreach ($contexts as $context) {
    1308                  switch ($context->contextlevel) {
    1309                      case CONTEXT_MODULE :
    1310                          $contextstring = 'module';
    1311                          break;
    1312                      case CONTEXT_COURSE :
    1313                          $contextstring = 'course';
    1314                          break;
    1315                      case CONTEXT_COURSECAT :
    1316                          $contextstring = "cat$catno";
    1317                          $catno++;
    1318                          break;
    1319                      case CONTEXT_SYSTEM :
    1320                          $contextstring = 'system';
    1321                          break;
    1322                  }
    1323                  $this->contexttostringarray[$context->id] = $contextstring;
    1324              }
    1325          }
    1326      }
    1327  
    1328  }
    1329  
    1330  /**
    1331   * Check capability on category
    1332   *
    1333   * @param mixed $question object or id
    1334   * @param string $cap 'add', 'edit', 'view', 'use', 'move'
    1335   * @param integer $cachecat useful to cache all question records in a category
    1336   * @return boolean this user has the capability $cap for this question $question?
    1337   */
    1338  function question_has_capability_on($question, $cap, $cachecat = -1) {
    1339      global $USER, $DB;
    1340  
    1341      // these are capabilities on existing questions capabilties are
    1342      //set per category. Each of these has a mine and all version. Append 'mine' and 'all'
    1343      $question_questioncaps = array('edit', 'view', 'use', 'move');
    1344      static $questions = array();
    1345      static $categories = array();
    1346      static $cachedcat = array();
    1347      if ($cachecat != -1 && array_search($cachecat, $cachedcat) === false) {
    1348          $questions += $DB->get_records('question', array('category' => $cachecat), '', 'id,category,createdby');
    1349          $cachedcat[] = $cachecat;
    1350      }
    1351      if (!is_object($question)) {
    1352          if (!isset($questions[$question])) {
    1353              if (!$questions[$question] = $DB->get_record('question',
    1354                      array('id' => $question), 'id,category,createdby')) {
    1355                  print_error('questiondoesnotexist', 'question');
    1356              }
    1357          }
    1358          $question = $questions[$question];
    1359      }
    1360      if (empty($question->category)) {
    1361          // This can happen when we have created a fake 'missingtype' question to
    1362          // take the place of a deleted question.
    1363          return false;
    1364      }
    1365      if (!isset($categories[$question->category])) {
    1366          if (!$categories[$question->category] = $DB->get_record('question_categories',
    1367                  array('id'=>$question->category))) {
    1368              print_error('invalidcategory', 'question');
    1369          }
    1370      }
    1371      $category = $categories[$question->category];
    1372      $context = context::instance_by_id($category->contextid);
    1373  
    1374      if (array_search($cap, $question_questioncaps)!== false) {
    1375          if (!has_capability('moodle/question:' . $cap . 'all', $context)) {
    1376              if ($question->createdby == $USER->id) {
    1377                  return has_capability('moodle/question:' . $cap . 'mine', $context);
    1378              } else {
    1379                  return false;
    1380              }
    1381          } else {
    1382              return true;
    1383          }
    1384      } else {
    1385          return has_capability('moodle/question:' . $cap, $context);
    1386      }
    1387  
    1388  }
    1389  
    1390  /**
    1391   * Require capability on question.
    1392   */
    1393  function question_require_capability_on($question, $cap) {
    1394      if (!question_has_capability_on($question, $cap)) {
    1395          print_error('nopermissions', '', '', $cap);
    1396      }
    1397      return true;
    1398  }
    1399  
    1400  /**
    1401   * Get the real state - the correct question id and answer - for a random
    1402   * question.
    1403   * @param object $state with property answer.
    1404   * @deprecated this function has not been relevant since Moodle 2.1!
    1405   */
    1406  function question_get_real_state($state) {
    1407      throw new coding_exception('question_get_real_state has not been relevant since Moodle 2.1. ' .
    1408              'I am not sure what you are trying to do, but stop it at once!');
    1409  }
    1410  
    1411  /**
    1412   * @param object $context a context
    1413   * @return string A URL for editing questions in this context.
    1414   */
    1415  function question_edit_url($context) {
    1416      global $CFG, $SITE;
    1417      if (!has_any_capability(question_get_question_capabilities(), $context)) {
    1418          return false;
    1419      }
    1420      $baseurl = $CFG->wwwroot . '/question/edit.php?';
    1421      $defaultcategory = question_get_default_category($context->id);
    1422      if ($defaultcategory) {
    1423          $baseurl .= 'cat=' . $defaultcategory->id . ',' . $context->id . '&amp;';
    1424      }
    1425      switch ($context->contextlevel) {
    1426          case CONTEXT_SYSTEM:
    1427              return $baseurl . 'courseid=' . $SITE->id;
    1428          case CONTEXT_COURSECAT:
    1429              // This is nasty, becuase we can only edit questions in a course
    1430              // context at the moment, so for now we just return false.
    1431              return false;
    1432          case CONTEXT_COURSE:
    1433              return $baseurl . 'courseid=' . $context->instanceid;
    1434          case CONTEXT_MODULE:
    1435              return $baseurl . 'cmid=' . $context->instanceid;
    1436      }
    1437  
    1438  }
    1439  
    1440  /**
    1441   * Adds question bank setting links to the given navigation node if caps are met.
    1442   *
    1443   * @param navigation_node $navigationnode The navigation node to add the question branch to
    1444   * @param object $context
    1445   * @return navigation_node Returns the question branch that was added
    1446   */
    1447  function question_extend_settings_navigation(navigation_node $navigationnode, $context) {
    1448      global $PAGE;
    1449  
    1450      if ($context->contextlevel == CONTEXT_COURSE) {
    1451          $params = array('courseid'=>$context->instanceid);
    1452      } else if ($context->contextlevel == CONTEXT_MODULE) {
    1453          $params = array('cmid'=>$context->instanceid);
    1454      } else {
    1455          return;
    1456      }
    1457  
    1458      if (($cat = $PAGE->url->param('cat')) && preg_match('~\d+,\d+~', $cat)) {
    1459          $params['cat'] = $cat;
    1460      }
    1461  
    1462      $questionnode = $navigationnode->add(get_string('questionbank', 'question'),
    1463              new moodle_url('/question/edit.php', $params), navigation_node::TYPE_CONTAINER);
    1464  
    1465      $contexts = new question_edit_contexts($context);
    1466      if ($contexts->have_one_edit_tab_cap('questions')) {
    1467          $questionnode->add(get_string('questions', 'question'), new moodle_url(
    1468                  '/question/edit.php', $params), navigation_node::TYPE_SETTING);
    1469      }
    1470      if ($contexts->have_one_edit_tab_cap('categories')) {
    1471          $questionnode->add(get_string('categories', 'question'), new moodle_url(
    1472                  '/question/category.php', $params), navigation_node::TYPE_SETTING);
    1473      }
    1474      if ($contexts->have_one_edit_tab_cap('import')) {
    1475          $questionnode->add(get_string('import', 'question'), new moodle_url(
    1476                  '/question/import.php', $params), navigation_node::TYPE_SETTING);
    1477      }
    1478      if ($contexts->have_one_edit_tab_cap('export')) {
    1479          $questionnode->add(get_string('export', 'question'), new moodle_url(
    1480                  '/question/export.php', $params), navigation_node::TYPE_SETTING);
    1481      }
    1482  
    1483      return $questionnode;
    1484  }
    1485  
    1486  /**
    1487   * @return array all the capabilities that relate to accessing particular questions.
    1488   */
    1489  function question_get_question_capabilities() {
    1490      return array(
    1491          'moodle/question:add',
    1492          'moodle/question:editmine',
    1493          'moodle/question:editall',
    1494          'moodle/question:viewmine',
    1495          'moodle/question:viewall',
    1496          'moodle/question:usemine',
    1497          'moodle/question:useall',
    1498          'moodle/question:movemine',
    1499          'moodle/question:moveall',
    1500      );
    1501  }
    1502  
    1503  /**
    1504   * @return array all the question bank capabilities.
    1505   */
    1506  function question_get_all_capabilities() {
    1507      $caps = question_get_question_capabilities();
    1508      $caps[] = 'moodle/question:managecategory';
    1509      $caps[] = 'moodle/question:flag';
    1510      return $caps;
    1511  }
    1512  
    1513  
    1514  /**
    1515   * Tracks all the contexts related to the one where we are currently editing
    1516   * questions, and provides helper methods to check permissions.
    1517   *
    1518   * @copyright 2007 Jamie Pratt me@jamiep.org
    1519   * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
    1520   */
    1521  class question_edit_contexts {
    1522  
    1523      public static $caps = array(
    1524          'editq' => array('moodle/question:add',
    1525              'moodle/question:editmine',
    1526              'moodle/question:editall',
    1527              'moodle/question:viewmine',
    1528              'moodle/question:viewall',
    1529              'moodle/question:usemine',
    1530              'moodle/question:useall',
    1531              'moodle/question:movemine',
    1532              'moodle/question:moveall'),
    1533          'questions'=>array('moodle/question:add',
    1534              'moodle/question:editmine',
    1535              'moodle/question:editall',
    1536              'moodle/question:viewmine',
    1537              'moodle/question:viewall',
    1538              'moodle/question:movemine',
    1539              'moodle/question:moveall'),
    1540          'categories'=>array('moodle/question:managecategory'),
    1541          'import'=>array('moodle/question:add'),
    1542          'export'=>array('moodle/question:viewall', 'moodle/question:viewmine'));
    1543  
    1544      protected $allcontexts;
    1545  
    1546      /**
    1547       * Constructor
    1548       * @param context the current context.
    1549       */
    1550      public function __construct(context $thiscontext) {
    1551          $this->allcontexts = array_values($thiscontext->get_parent_contexts(true));
    1552      }
    1553  
    1554      /**
    1555       * @return array all parent contexts
    1556       */
    1557      public function all() {
    1558          return $this->allcontexts;
    1559      }
    1560  
    1561      /**
    1562       * @return object lowest context which must be either the module or course context
    1563       */
    1564      public function lowest() {
    1565          return $this->allcontexts[0];
    1566      }
    1567  
    1568      /**
    1569       * @param string $cap capability
    1570       * @return array parent contexts having capability, zero based index
    1571       */
    1572      public function having_cap($cap) {
    1573          $contextswithcap = array();
    1574          foreach ($this->allcontexts as $context) {
    1575              if (has_capability($cap, $context)) {
    1576                  $contextswithcap[] = $context;
    1577              }
    1578          }
    1579          return $contextswithcap;
    1580      }
    1581  
    1582      /**
    1583       * @param array $caps capabilities
    1584       * @return array parent contexts having at least one of $caps, zero based index
    1585       */
    1586      public function having_one_cap($caps) {
    1587          $contextswithacap = array();
    1588          foreach ($this->allcontexts as $context) {
    1589              foreach ($caps as $cap) {
    1590                  if (has_capability($cap, $context)) {
    1591                      $contextswithacap[] = $context;
    1592                      break; //done with caps loop
    1593                  }
    1594              }
    1595          }
    1596          return $contextswithacap;
    1597      }
    1598  
    1599      /**
    1600       * @param string $tabname edit tab name
    1601       * @return array parent contexts having at least one of $caps, zero based index
    1602       */
    1603      public function having_one_edit_tab_cap($tabname) {
    1604          return $this->having_one_cap(self::$caps[$tabname]);
    1605      }
    1606  
    1607      /**
    1608       * @return those contexts where a user can add a question and then use it.
    1609       */
    1610      public function having_add_and_use() {
    1611          $contextswithcap = array();
    1612          foreach ($this->allcontexts as $context) {
    1613              if (!has_capability('moodle/question:add', $context)) {
    1614                  continue;
    1615              }
    1616              if (!has_any_capability(array('moodle/question:useall', 'moodle/question:usemine'), $context)) {
    1617                              continue;
    1618              }
    1619              $contextswithcap[] = $context;
    1620          }
    1621          return $contextswithcap;
    1622      }
    1623  
    1624      /**
    1625       * Has at least one parent context got the cap $cap?
    1626       *
    1627       * @param string $cap capability
    1628       * @return boolean
    1629       */
    1630      public function have_cap($cap) {
    1631          return (count($this->having_cap($cap)));
    1632      }
    1633  
    1634      /**
    1635       * Has at least one parent context got one of the caps $caps?
    1636       *
    1637       * @param array $caps capability
    1638       * @return boolean
    1639       */
    1640      public function have_one_cap($caps) {
    1641          foreach ($caps as $cap) {
    1642              if ($this->have_cap($cap)) {
    1643                  return true;
    1644              }
    1645          }
    1646          return false;
    1647      }
    1648  
    1649      /**
    1650       * Has at least one parent context got one of the caps for actions on $tabname
    1651       *
    1652       * @param string $tabname edit tab name
    1653       * @return boolean
    1654       */
    1655      public function have_one_edit_tab_cap($tabname) {
    1656          return $this->have_one_cap(self::$caps[$tabname]);
    1657      }
    1658  
    1659      /**
    1660       * Throw error if at least one parent context hasn't got the cap $cap
    1661       *
    1662       * @param string $cap capability
    1663       */
    1664      public function require_cap($cap) {
    1665          if (!$this->have_cap($cap)) {
    1666              print_error('nopermissions', '', '', $cap);
    1667          }
    1668      }
    1669  
    1670      /**
    1671       * Throw error if at least one parent context hasn't got one of the caps $caps
    1672       *
    1673       * @param array $cap capabilities
    1674       */
    1675      public function require_one_cap($caps) {
    1676          if (!$this->have_one_cap($caps)) {
    1677              $capsstring = join($caps, ', ');
    1678              print_error('nopermissions', '', '', $capsstring);
    1679          }
    1680      }
    1681  
    1682      /**
    1683       * Throw error if at least one parent context hasn't got one of the caps $caps
    1684       *
    1685       * @param string $tabname edit tab name
    1686       */
    1687      public function require_one_edit_tab_cap($tabname) {
    1688          if (!$this->have_one_edit_tab_cap($tabname)) {
    1689              print_error('nopermissions', '', '', 'access question edit tab '.$tabname);
    1690          }
    1691      }
    1692  }
    1693  
    1694  
    1695  /**
    1696   * Helps call file_rewrite_pluginfile_urls with the right parameters.
    1697   *
    1698   * @package  core_question
    1699   * @category files
    1700   * @param string $text text being processed
    1701   * @param string $file the php script used to serve files
    1702   * @param int $contextid context ID
    1703   * @param string $component component
    1704   * @param string $filearea filearea
    1705   * @param array $ids other IDs will be used to check file permission
    1706   * @param int $itemid item ID
    1707   * @param array $options options
    1708   * @return string
    1709   */
    1710  function question_rewrite_question_urls($text, $file, $contextid, $component,
    1711          $filearea, array $ids, $itemid, array $options=null) {
    1712  
    1713      $idsstr = '';
    1714      if (!empty($ids)) {
    1715          $idsstr .= implode('/', $ids);
    1716      }
    1717      if ($itemid !== null) {
    1718          $idsstr .= '/' . $itemid;
    1719      }
    1720      return file_rewrite_pluginfile_urls($text, $file, $contextid, $component,
    1721              $filearea, $idsstr, $options);
    1722  }
    1723  
    1724  /**
    1725   * Rewrite the PLUGINFILE urls in the questiontext, when viewing the question
    1726   * text outside an attempt (for example, in the question bank listing or in the
    1727   * quiz statistics report).
    1728   *
    1729   * @param string $questiontext the question text.
    1730   * @param int $contextid the context the text is being displayed in.
    1731   * @param string $component component
    1732   * @param array $questionid the question id
    1733   * @param array $options e.g. forcedownload. Passed to file_rewrite_pluginfile_urls.
    1734   * @return string $questiontext with URLs rewritten.
    1735   * @deprecated since Moodle 2.6
    1736   */
    1737  function question_rewrite_questiontext_preview_urls($questiontext, $contextid,
    1738          $component, $questionid, $options=null) {
    1739      global $DB;
    1740  
    1741      debugging('question_rewrite_questiontext_preview_urls has been deprecated. ' .
    1742              'Please use question_rewrite_question_preview_urls instead', DEBUG_DEVELOPER);
    1743      $questioncontextid = $DB->get_field_sql('
    1744              SELECT qc.contextid
    1745                FROM {question} q
    1746                JOIN {question_categories} qc ON qc.id = q.category
    1747               WHERE q.id = :id', array('id' => $questionid), MUST_EXIST);
    1748  
    1749      return question_rewrite_question_preview_urls($questiontext, $questionid,
    1750              $questioncontextid, 'question', 'questiontext', $questionid,
    1751              $contextid, $component, $options);
    1752  }
    1753  
    1754  /**
    1755   * Rewrite the PLUGINFILE urls in part of the content of a question, for use when
    1756   * viewing the question outside an attempt (for example, in the question bank
    1757   * listing or in the quiz statistics report).
    1758   *
    1759   * @param string $text the question text.
    1760   * @param int $questionid the question id.
    1761   * @param int $filecontextid the context id of the question being displayed.
    1762   * @param string $filecomponent the component that owns the file area.
    1763   * @param string $filearea the file area name.
    1764   * @param int|null $itemid the file's itemid
    1765   * @param int $previewcontextid the context id where the preview is being displayed.
    1766   * @param string $previewcomponent component responsible for displaying the preview.
    1767   * @param array $options text and file options ('forcehttps'=>false)
    1768   * @return string $questiontext with URLs rewritten.
    1769   */
    1770  function question_rewrite_question_preview_urls($text, $questionid,
    1771          $filecontextid, $filecomponent, $filearea, $itemid,
    1772          $previewcontextid, $previewcomponent, $options = null) {
    1773  
    1774      $path = "preview/$previewcontextid/$previewcomponent/$questionid";
    1775      if ($itemid) {
    1776          $path .= '/' . $itemid;
    1777      }
    1778  
    1779      return file_rewrite_pluginfile_urls($text, 'pluginfile.php', $filecontextid,
    1780              $filecomponent, $filearea, $path, $options);
    1781  }
    1782  
    1783  /**
    1784   * Send a file from the question text of a question.
    1785   * @param int $questionid the question id
    1786   * @param array $args the remaining file arguments (file path).
    1787   * @param bool $forcedownload whether the user must be forced to download the file.
    1788   * @param array $options additional options affecting the file serving
    1789   * @deprecated since Moodle 2.6.
    1790   */
    1791  function question_send_questiontext_file($questionid, $args, $forcedownload, $options) {
    1792      global $DB;
    1793  
    1794      debugging('question_send_questiontext_file has been deprecated. It is no longer necessary. ' .
    1795              'You can now just use send_stored_file.', DEBUG_DEVELOPER);
    1796      $question = $DB->get_record_sql('
    1797              SELECT q.id, qc.contextid
    1798                FROM {question} q
    1799                JOIN {question_categories} qc ON qc.id = q.category
    1800               WHERE q.id = :id', array('id' => $questionid), MUST_EXIST);
    1801  
    1802      $fs = get_file_storage();
    1803      $fullpath = "/$question->contextid/question/questiontext/$question->id/" . implode('/', $args);
    1804  
    1805      // Get rid of the redundant questionid.
    1806      $fullpath = str_replace("/{$questionid}/{$questionid}/", "/{$questionid}/", $fullpath);
    1807  
    1808      if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
    1809          send_file_not_found();
    1810      }
    1811  
    1812      send_stored_file($file, 0, 0, $forcedownload, $options);
    1813  }
    1814  
    1815  /**
    1816   * Called by pluginfile.php to serve files related to the 'question' core
    1817   * component and for files belonging to qtypes.
    1818   *
    1819   * For files that relate to questions in a question_attempt, then we delegate to
    1820   * a function in the component that owns the attempt (for example in the quiz,
    1821   * or in core question preview) to get necessary inforation.
    1822   *
    1823   * (Note that, at the moment, all question file areas relate to questions in
    1824   * attempts, so the If at the start of the last paragraph is always true.)
    1825   *
    1826   * Does not return, either calls send_file_not_found(); or serves the file.
    1827   *
    1828   * @package  core_question
    1829   * @category files
    1830   * @param stdClass $course course settings object
    1831   * @param stdClass $context context object
    1832   * @param string $component the name of the component we are serving files for.
    1833   * @param string $filearea the name of the file area.
    1834   * @param array $args the remaining bits of the file path.
    1835   * @param bool $forcedownload whether the user must be forced to download the file.
    1836   * @param array $options additional options affecting the file serving
    1837   */
    1838  function question_pluginfile($course, $context, $component, $filearea, $args, $forcedownload, array $options=array()) {
    1839      global $DB, $CFG;
    1840  
    1841      // Special case, sending a question bank export.
    1842      if ($filearea === 'export') {
    1843          list($context, $course, $cm) = get_context_info_array($context->id);
    1844          require_login($course, false, $cm);
    1845  
    1846          require_once($CFG->dirroot . '/question/editlib.php');
    1847          $contexts = new question_edit_contexts($context);
    1848          // check export capability
    1849          $contexts->require_one_edit_tab_cap('export');
    1850          $category_id = (int)array_shift($args);
    1851          $format      = array_shift($args);
    1852          $cattofile   = array_shift($args);
    1853          $contexttofile = array_shift($args);
    1854          $filename    = array_shift($args);
    1855  
    1856          // load parent class for import/export
    1857          require_once($CFG->dirroot . '/question/format.php');
    1858          require_once($CFG->dirroot . '/question/editlib.php');
    1859          require_once($CFG->dirroot . '/question/format/' . $format . '/format.php');
    1860  
    1861          $classname = 'qformat_' . $format;
    1862          if (!class_exists($classname)) {
    1863              send_file_not_found();
    1864          }
    1865  
    1866          $qformat = new $classname();
    1867  
    1868          if (!$category = $DB->get_record('question_categories', array('id' => $category_id))) {
    1869              send_file_not_found();
    1870          }
    1871  
    1872          $qformat->setCategory($category);
    1873          $qformat->setContexts($contexts->having_one_edit_tab_cap('export'));
    1874          $qformat->setCourse($course);
    1875  
    1876          if ($cattofile == 'withcategories') {
    1877              $qformat->setCattofile(true);
    1878          } else {
    1879              $qformat->setCattofile(false);
    1880          }
    1881  
    1882          if ($contexttofile == 'withcontexts') {
    1883              $qformat->setContexttofile(true);
    1884          } else {
    1885              $qformat->setContexttofile(false);
    1886          }
    1887  
    1888          if (!$qformat->exportpreprocess()) {
    1889              send_file_not_found();
    1890              print_error('exporterror', 'question', $thispageurl->out());
    1891          }
    1892  
    1893          // export data to moodle file pool
    1894          if (!$content = $qformat->exportprocess(true)) {
    1895              send_file_not_found();
    1896          }
    1897  
    1898          send_file($content, $filename, 0, 0, true, true, $qformat->mime_type());
    1899      }
    1900  
    1901      // Normal case, a file belonging to a question.
    1902      $qubaidorpreview = array_shift($args);
    1903  
    1904      // Two sub-cases: 1. A question being previewed outside an attempt/usage.
    1905      if ($qubaidorpreview === 'preview') {
    1906          $previewcontextid = (int)array_shift($args);
    1907          $previewcomponent = array_shift($args);
    1908          $questionid = (int) array_shift($args);
    1909          $previewcontext = context_helper::instance_by_id($previewcontextid);
    1910  
    1911          $result = component_callback($previewcomponent, 'question_preview_pluginfile', array(
    1912                  $previewcontext, $questionid,
    1913                  $context, $component, $filearea, $args,
    1914                  $forcedownload, $options), 'newcallbackmissing');
    1915  
    1916          if ($result === 'newcallbackmissing' && $filearea = 'questiontext') {
    1917              // Fall back to the legacy callback for backwards compatibility.
    1918              debugging("Component {$previewcomponent} does not define the expected " .
    1919                      "{$previewcomponent}_question_preview_pluginfile callback. Falling back to the deprecated " .
    1920                      "{$previewcomponent}_questiontext_preview_pluginfile callback.", DEBUG_DEVELOPER);
    1921              component_callback($previewcomponent, 'questiontext_preview_pluginfile', array(
    1922                      $previewcontext, $questionid, $args, $forcedownload, $options));
    1923          }
    1924  
    1925          send_file_not_found();
    1926      }
    1927  
    1928      // 2. A question being attempted in the normal way.
    1929      $qubaid = (int)$qubaidorpreview;
    1930      $slot = (int)array_shift($args);
    1931  
    1932      $module = $DB->get_field('question_usages', 'component',
    1933              array('id' => $qubaid));
    1934      if (!$module) {
    1935          send_file_not_found();
    1936      }
    1937  
    1938      if ($module === 'core_question_preview') {
    1939          require_once($CFG->dirroot . '/question/previewlib.php');
    1940          return question_preview_question_pluginfile($course, $context,
    1941                  $component, $filearea, $qubaid, $slot, $args, $forcedownload, $options);
    1942  
    1943      } else {
    1944          $dir = core_component::get_component_directory($module);
    1945          if (!file_exists("$dir/lib.php")) {
    1946              send_file_not_found();
    1947          }
    1948          include_once("$dir/lib.php");
    1949  
    1950          $filefunction = $module . '_question_pluginfile';
    1951          if (function_exists($filefunction)) {
    1952              $filefunction($course, $context, $component, $filearea, $qubaid, $slot,
    1953                  $args, $forcedownload, $options);
    1954          }
    1955  
    1956          // Okay, we're here so lets check for function without 'mod_'.
    1957          if (strpos($module, 'mod_') === 0) {
    1958              $filefunctionold  = substr($module, 4) . '_question_pluginfile';
    1959              if (function_exists($filefunctionold)) {
    1960                  $filefunctionold($course, $context, $component, $filearea, $qubaid, $slot,
    1961                      $args, $forcedownload, $options);
    1962              }
    1963          }
    1964  
    1965          send_file_not_found();
    1966      }
    1967  }
    1968  
    1969  /**
    1970   * Serve questiontext files in the question text when they are displayed in this report.
    1971   *
    1972   * @package  core_files
    1973   * @category files
    1974   * @param context $previewcontext the context in which the preview is happening.
    1975   * @param int $questionid the question id.
    1976   * @param context $filecontext the file (question) context.
    1977   * @param string $filecomponent the component the file belongs to.
    1978   * @param string $filearea the file area.
    1979   * @param array $args remaining file args.
    1980   * @param bool $forcedownload.
    1981   * @param array $options additional options affecting the file serving.
    1982   */
    1983  function core_question_question_preview_pluginfile($previewcontext, $questionid,
    1984          $filecontext, $filecomponent, $filearea, $args, $forcedownload, $options = array()) {
    1985      global $DB;
    1986  
    1987      // Verify that contextid matches the question.
    1988      $question = $DB->get_record_sql('
    1989              SELECT q.*, qc.contextid
    1990                FROM {question} q
    1991                JOIN {question_categories} qc ON qc.id = q.category
    1992               WHERE q.id = :id AND qc.contextid = :contextid',
    1993              array('id' => $questionid, 'contextid' => $filecontext->id), MUST_EXIST);
    1994  
    1995      // Check the capability.
    1996      list($context, $course, $cm) = get_context_info_array($previewcontext->id);
    1997      require_login($course, false, $cm);
    1998  
    1999      question_require_capability_on($question, 'use');
    2000  
    2001      $fs = get_file_storage();
    2002      $relativepath = implode('/', $args);
    2003      $fullpath = "/{$filecontext->id}/{$filecomponent}/{$filearea}/{$relativepath}";
    2004      if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
    2005          send_file_not_found();
    2006      }
    2007  
    2008      send_stored_file($file, 0, 0, $forcedownload, $options);
    2009  }
    2010  
    2011  /**
    2012   * Create url for question export
    2013   *
    2014   * @param int $contextid, current context
    2015   * @param int $categoryid, categoryid
    2016   * @param string $format
    2017   * @param string $withcategories
    2018   * @param string $ithcontexts
    2019   * @param moodle_url export file url
    2020   */
    2021  function question_make_export_url($contextid, $categoryid, $format, $withcategories,
    2022          $withcontexts, $filename) {
    2023      global $CFG;
    2024      $urlbase = "$CFG->httpswwwroot/pluginfile.php";
    2025      return moodle_url::make_file_url($urlbase,
    2026              "/$contextid/question/export/{$categoryid}/{$format}/{$withcategories}" .
    2027              "/{$withcontexts}/{$filename}", true);
    2028  }
    2029  
    2030  /**
    2031   * Return a list of page types
    2032   * @param string $pagetype current page type
    2033   * @param stdClass $parentcontext Block's parent context
    2034   * @param stdClass $currentcontext Current context of block
    2035   */
    2036  function question_page_type_list($pagetype, $parentcontext, $currentcontext) {
    2037      global $CFG;
    2038      $types = array(
    2039          'question-*'=>get_string('page-question-x', 'question'),
    2040          'question-edit'=>get_string('page-question-edit', 'question'),
    2041          'question-category'=>get_string('page-question-category', 'question'),
    2042          'question-export'=>get_string('page-question-export', 'question'),
    2043          'question-import'=>get_string('page-question-import', 'question')
    2044      );
    2045      if ($currentcontext->contextlevel == CONTEXT_COURSE) {
    2046          require_once($CFG->dirroot . '/course/lib.php');
    2047          return array_merge(course_page_type_list($pagetype, $parentcontext, $currentcontext), $types);
    2048      } else {
    2049          return $types;
    2050      }
    2051  }
    2052  
    2053  /**
    2054   * Does an activity module use the question bank?
    2055   *
    2056   * @param string $modname The name of the module (without mod_ prefix).
    2057   * @return bool true if the module uses questions.
    2058   */
    2059  function question_module_uses_questions($modname) {
    2060      if (plugin_supports('mod', $modname, FEATURE_USES_QUESTIONS)) {
    2061          return true;
    2062      }
    2063  
    2064      $component = 'mod_'.$modname;
    2065      if (component_callback_exists($component, 'question_pluginfile')) {
    2066          debugging("{$component} uses questions but doesn't declare FEATURE_USES_QUESTIONS", DEBUG_DEVELOPER);
    2067          return true;
    2068      }
    2069  
    2070      return false;
    2071  }
    

    Search This Site: