Search moodle.org's
Developer Documentation

See Release Notes
Long Term Support Release

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

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

   1  <?php
   2  // This file is part of Moodle - http://moodle.org/
   3  //
   4  // Moodle is free software: you can redistribute it and/or modify
   5  // it under the terms of the GNU General Public License as published by
   6  // the Free Software Foundation, either version 3 of the License, or
   7  // (at your option) any later version.
   8  //
   9  // Moodle is distributed in the hope that it will be useful,
  10  // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  12  // GNU General Public License for more details.
  13  //
  14  // You should have received a copy of the GNU General Public License
  15  // along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
  16  
  17  
  18  /**
  19   * External question API
  20   *
  21   * @package    core_question
  22   * @category   external
  23   * @copyright  2016 Pau Ferrer <pau@moodle.com>
  24   * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  25   */
  26  
  27  defined('MOODLE_INTERNAL') || die();
  28  
  29  require_once("$CFG->libdir/externallib.php");
  30  require_once($CFG->dirroot . '/question/engine/lib.php');
  31  require_once($CFG->dirroot . '/question/engine/datalib.php');
  32  require_once($CFG->libdir . '/questionlib.php');
  33  
  34  /**
  35   * Question external functions
  36   *
  37   * @package    core_question
  38   * @category   external
  39   * @copyright  2016 Pau Ferrer <pau@moodle.com>
  40   * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  41   * @since Moodle 3.1
  42   */
  43  class core_question_external extends external_api {
  44  
  45      /**
  46       * Returns description of method parameters
  47       *
  48       * @return external_function_parameters
  49       * @since Moodle 3.1
  50       */
  51      public static function update_flag_parameters() {
  52          return new external_function_parameters(
  53              array(
  54                  'qubaid' => new external_value(PARAM_INT, 'the question usage id.'),
  55                  'questionid' => new external_value(PARAM_INT, 'the question id'),
  56                  'qaid' => new external_value(PARAM_INT, 'the question_attempt id'),
  57                  'slot' => new external_value(PARAM_INT, 'the slot number within the usage'),
  58                  'checksum' => new external_value(PARAM_ALPHANUM, 'computed checksum with the last three arguments and
  59                               the users username'),
  60                  'newstate' => new external_value(PARAM_BOOL, 'the new state of the flag. true = flagged')
  61              )
  62          );
  63      }
  64  
  65      /**
  66       * Update the flag state of a question attempt.
  67       *
  68       * @param int $qubaid the question usage id.
  69       * @param int $questionid the question id.
  70       * @param int $qaid the question_attempt id.
  71       * @param int $slot the slot number within the usage.
  72       * @param string $checksum checksum, as computed by {@link get_toggle_checksum()}
  73       *      corresponding to the last three arguments and the users username.
  74       * @param bool $newstate the new state of the flag. true = flagged.
  75       * @return array (success infos and fail infos)
  76       * @since Moodle 3.1
  77       */
  78      public static function update_flag($qubaid, $questionid, $qaid, $slot, $checksum, $newstate) {
  79          global $CFG, $DB;
  80  
  81          $params = self::validate_parameters(self::update_flag_parameters(),
  82              array(
  83                  'qubaid' => $qubaid,
  84                  'questionid' => $questionid,
  85                  'qaid' => $qaid,
  86                  'slot' => $slot,
  87                  'checksum' => $checksum,
  88                  'newstate' => $newstate
  89              )
  90          );
  91  
  92          $warnings = array();
  93          self::validate_context(context_system::instance());
  94  
  95          // The checksum will be checked to provide security flagging other users questions.
  96          question_flags::update_flag($params['qubaid'], $params['questionid'], $params['qaid'], $params['slot'], $params['checksum'],
  97                                      $params['newstate']);
  98  
  99          $result = array();
 100          $result['status'] = true;
 101          $result['warnings'] = $warnings;
 102          return $result;
 103      }
 104  
 105      /**
 106       * Returns description of method result value
 107       *
 108       * @return external_description
 109       * @since Moodle 3.1
 110       */
 111      public static function update_flag_returns() {
 112          return new external_single_structure(
 113              array(
 114                  'status' => new external_value(PARAM_BOOL, 'status: true if success'),
 115                  'warnings' => new external_warnings()
 116              )
 117          );
 118      }
 119  
 120      /**
 121       * Returns description of method parameters.
 122       *
 123       * @return external_function_parameters.
 124       * @deprecated since Moodle 4.0
 125       * @see \qbank_tagquestion\external\qbank_tagquestion_external
 126       * @todo Final deprecation on Moodle 4.4 MDL-72438
 127       */
 128      public static function submit_tags_form_parameters() {
 129          return new external_function_parameters([
 130                  'questionid' => new external_value(PARAM_INT, 'The question id'),
 131                  'contextid' => new external_value(PARAM_INT, 'The editing context id'),
 132                  'formdata' => new external_value(PARAM_RAW, 'The data from the tag form'),
 133          ]);
 134      }
 135  
 136      /**
 137       * Handles the tags form submission.
 138       *
 139       * @param int $questionid The question id.
 140       * @param int $contextid The editing context id.
 141       * @param string $formdata The question tag form data in a URI encoded param string
 142       * @return array The created or modified question tag
 143       * @deprecated since Moodle 4.0
 144       * @see \qbank_tagquestion\external\qbank_tagquestion_external
 145       * @todo Final deprecation on Moodle 4.4 MDL-72438
 146       */
 147      public static function submit_tags_form($questionid, $contextid, $formdata) {
 148          global $DB, $CFG;
 149  
 150          $data = [];
 151          $result = ['status' => false];
 152  
 153          // Parameter validation.
 154          $params = self::validate_parameters(self::submit_tags_form_parameters(), [
 155              'questionid' => $questionid,
 156              'contextid' => $contextid,
 157              'formdata' => $formdata
 158          ]);
 159  
 160          $editingcontext = \context::instance_by_id($contextid);
 161          self::validate_context($editingcontext);
 162          parse_str($params['formdata'], $data);
 163  
 164          if (!$question = $DB->get_record_sql('
 165                  SELECT q.*, qc.contextid
 166                  FROM {question} q
 167                  JOIN {question_categories} qc ON qc.id = q.category
 168                  WHERE q.id = ?', [$questionid])) {
 169              throw new \moodle_exception('questiondoesnotexist', 'question');
 170          }
 171  
 172          require_once($CFG->libdir . '/questionlib.php');
 173  
 174          $cantag = question_has_capability_on($question, 'tag');
 175          $questioncontext = \context::instance_by_id($question->contextid);
 176          $contexts = new \core_question\local\bank\question_edit_contexts($editingcontext);
 177  
 178          $formoptions = [
 179              'editingcontext' => $editingcontext,
 180              'questioncontext' => $questioncontext,
 181              'contexts' => $contexts->all()
 182          ];
 183  
 184          $mform = new \qbank_tagquestion\form\tags_form(null, $formoptions, 'post', '', null, $cantag, $data);
 185  
 186          if ($validateddata = $mform->get_data()) {
 187              if ($cantag) {
 188                  if (isset($validateddata->tags)) {
 189                      // Due to a mform bug, if there's no tags set on the tag element, it submits the name as the value.
 190                      // The only way to discover is checking if the tag element is an array.
 191                      $tags = is_array($validateddata->tags) ? $validateddata->tags : [];
 192  
 193                      core_tag_tag::set_item_tags('core_question', 'question', $validateddata->id,
 194                          $questioncontext, $tags);
 195  
 196                      $result['status'] = true;
 197                  }
 198  
 199                  if (isset($validateddata->coursetags)) {
 200                      $coursetags = is_array($validateddata->coursetags) ? $validateddata->coursetags : [];
 201                      core_tag_tag::set_item_tags('core_question', 'question', $validateddata->id,
 202                          $editingcontext->get_course_context(false), $coursetags);
 203  
 204                      $result['status'] = true;
 205                  }
 206              }
 207          }
 208  
 209          return $result;
 210      }
 211  
 212      /**
 213       * Returns description of method result value.
 214       *
 215       * @deprecated since Moodle 4.0
 216       * @see \qbank_tagquestion\external\qbank_tagquestion_external
 217       * @todo Final deprecation on Moodle 4.4 MDL-72438
 218       */
 219      public static function  submit_tags_form_returns() {
 220          return new external_single_structure([
 221                  'status' => new external_value(PARAM_BOOL, 'status: true if success')
 222          ]);
 223      }
 224  
 225      /**
 226       * Marking the method as deprecated.
 227       *
 228       * @return bool
 229       * @todo Final deprecation on Moodle 4.4 MDL-72438
 230       */
 231      public static function submit_tags_form_is_deprecated() {
 232          return true;
 233      }
 234  
 235      /**
 236       * Returns description of method parameters.
 237       *
 238       * @return external_function_parameters.
 239       */
 240      public static function get_random_question_summaries_parameters() {
 241          return new external_function_parameters([
 242                  'categoryid' => new external_value(PARAM_INT, 'Category id to find random questions'),
 243                  'includesubcategories' => new external_value(PARAM_BOOL, 'Include the subcategories in the search'),
 244                  'tagids' => new external_multiple_structure(
 245                      new external_value(PARAM_INT, 'Tag id')
 246                  ),
 247                  'contextid' => new external_value(PARAM_INT,
 248                      'Context id that the questions will be rendered in (used for exporting)'),
 249                  'limit' => new external_value(PARAM_INT, 'Maximum number of results to return',
 250                      VALUE_DEFAULT, 0),
 251                  'offset' => new external_value(PARAM_INT, 'Number of items to skip from the begging of the result set',
 252                      VALUE_DEFAULT, 0)
 253          ]);
 254      }
 255  
 256      /**
 257       * Gets the list of random questions for the given criteria. The questions
 258       * will be exported in a summaries format and won't include all of the
 259       * question data.
 260       *
 261       * @param int $categoryid Category id to find random questions
 262       * @param bool $includesubcategories Include the subcategories in the search
 263       * @param int[] $tagids Only include questions with these tags
 264       * @param int $contextid The context id where the questions will be rendered
 265       * @param int $limit Maximum number of results to return
 266       * @param int $offset Number of items to skip from the beginning of the result set.
 267       * @return array The list of questions and total question count.
 268       */
 269      public static function get_random_question_summaries(
 270          $categoryid,
 271          $includesubcategories,
 272          $tagids,
 273          $contextid,
 274          $limit = 0,
 275          $offset = 0
 276      ) {
 277          global $DB, $PAGE;
 278  
 279          // Parameter validation.
 280          $params = self::validate_parameters(
 281              self::get_random_question_summaries_parameters(),
 282              [
 283                  'categoryid' => $categoryid,
 284                  'includesubcategories' => $includesubcategories,
 285                  'tagids' => $tagids,
 286                  'contextid' => $contextid,
 287                  'limit' => $limit,
 288                  'offset' => $offset
 289              ]
 290          );
 291          $categoryid = $params['categoryid'];
 292          $includesubcategories = $params['includesubcategories'];
 293          $tagids = $params['tagids'];
 294          $contextid = $params['contextid'];
 295          $limit = $params['limit'];
 296          $offset = $params['offset'];
 297  
 298          $context = \context::instance_by_id($contextid);
 299          self::validate_context($context);
 300  
 301          $categorycontextid = $DB->get_field('question_categories', 'contextid', ['id' => $categoryid], MUST_EXIST);
 302          $categorycontext = \context::instance_by_id($categorycontextid);
 303          $editcontexts = new \core_question\local\bank\question_edit_contexts($categorycontext);
 304          // The user must be able to view all questions in the category that they are requesting.
 305          $editcontexts->require_cap('moodle/question:viewall');
 306  
 307          $loader = new \core_question\local\bank\random_question_loader(new qubaid_list([]));
 308          // Only load the properties we require from the DB.
 309          $properties = \core_question\external\question_summary_exporter::get_mandatory_properties();
 310          $questions = $loader->get_questions($categoryid, $includesubcategories, $tagids, $limit, $offset, $properties);
 311          $totalcount = $loader->count_questions($categoryid, $includesubcategories, $tagids);
 312          $renderer = $PAGE->get_renderer('core');
 313  
 314          $formattedquestions = array_map(function($question) use ($context, $renderer) {
 315              $exporter = new \core_question\external\question_summary_exporter($question, ['context' => $context]);
 316              return $exporter->export($renderer);
 317          }, $questions);
 318  
 319          return [
 320              'totalcount' => $totalcount,
 321              'questions' => $formattedquestions
 322          ];
 323      }
 324  
 325      /**
 326       * Returns description of method result value.
 327       */
 328      public static function  get_random_question_summaries_returns() {
 329          return new external_single_structure([
 330              'totalcount' => new external_value(PARAM_INT, 'total number of questions in result set'),
 331              'questions' => new external_multiple_structure(
 332                  \core_question\external\question_summary_exporter::get_read_structure()
 333              )
 334          ]);
 335      }
 336  }