Merge branch 'MDL-61715-master' of https://github.com/lethevinh/moodle
[moodle.git] / question / classes / external.php
CommitLineData
7361b968
PFO
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
e71687ba
JL
27defined('MOODLE_INTERNAL') || die();
28
7361b968
PFO
29require_once("$CFG->libdir/externallib.php");
30require_once($CFG->dirroot . '/question/engine/lib.php');
6768729e 31require_once($CFG->dirroot . '/question/engine/datalib.php');
a9b34106 32require_once($CFG->libdir . '/questionlib.php');
7361b968
PFO
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 */
43class 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();
67ee1030 93 self::validate_context(context_system::instance());
7361b968
PFO
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 }
680d5c5b
SL
119
120 /**
121 * Returns description of method parameters.
122 *
123 * @return external_function_parameters.
124 */
125 public static function submit_tags_form_parameters() {
126 return new external_function_parameters([
e6890b11
SL
127 'questionid' => new external_value(PARAM_INT, 'The question id'),
128 'contextid' => new external_value(PARAM_INT, 'The editing context id'),
680d5c5b
SL
129 'formdata' => new external_value(PARAM_RAW, 'The data from the tag form'),
130 ]);
131 }
132
133 /**
134 * Handles the tags form submission.
135 *
e6890b11
SL
136 * @param int $questionid The question id.
137 * @param int $contextid The editing context id.
680d5c5b
SL
138 * @param string $formdata The question tag form data in a URI encoded param string
139 * @return array The created or modified question tag
680d5c5b 140 */
e6890b11
SL
141 public static function submit_tags_form($questionid, $contextid, $formdata) {
142 global $DB, $CFG;
680d5c5b
SL
143
144 $data = [];
145 $result = ['status' => false];
146
147 // Parameter validation.
e6890b11
SL
148 $params = self::validate_parameters(self::submit_tags_form_parameters(), [
149 'questionid' => $questionid,
150 'contextid' => $contextid,
151 'formdata' => $formdata
152 ]);
680d5c5b 153
e6890b11
SL
154 $editingcontext = \context::instance_by_id($contextid);
155 self::validate_context($editingcontext);
680d5c5b
SL
156 parse_str($params['formdata'], $data);
157
e6890b11
SL
158 if (!$question = $DB->get_record_sql('
159 SELECT q.*, qc.contextid
160 FROM {question} q
161 JOIN {question_categories} qc ON qc.id = q.category
162 WHERE q.id = ?', [$questionid])) {
163 print_error('questiondoesnotexist', 'question');
164 }
165
166 require_once($CFG->libdir . '/questionlib.php');
167 require_once($CFG->dirroot . '/question/type/tags_form.php');
680d5c5b 168
e6890b11
SL
169 $cantag = question_has_capability_on($question, 'tag');
170 $questioncontext = \context::instance_by_id($question->contextid);
a9b34106
SL
171 $contexts = new \question_edit_contexts($editingcontext);
172
e6890b11
SL
173 $formoptions = [
174 'editingcontext' => $editingcontext,
a9b34106
SL
175 'questioncontext' => $questioncontext,
176 'contexts' => $contexts->all()
e6890b11 177 ];
680d5c5b 178
e6890b11 179 $mform = new \core_question\form\tags(null, $formoptions, 'post', '', null, $cantag, $data);
680d5c5b 180
e6890b11
SL
181 if ($validateddata = $mform->get_data()) {
182 if ($cantag) {
183 if (isset($validateddata->tags)) {
184 // Due to a mform bug, if there's no tags set on the tag element, it submits the name as the value.
185 // The only way to discover is checking if the tag element is an array.
186 $tags = is_array($validateddata->tags) ? $validateddata->tags : [];
680d5c5b 187
e6890b11
SL
188 core_tag_tag::set_item_tags('core_question', 'question', $validateddata->id,
189 $questioncontext, $tags);
190
191 $result['status'] = true;
192 }
680d5c5b 193
e6890b11
SL
194 if (isset($validateddata->coursetags)) {
195 $coursetags = is_array($validateddata->coursetags) ? $validateddata->coursetags : [];
196 core_tag_tag::set_item_tags('core_question', 'question', $validateddata->id,
197 $editingcontext->get_course_context(false), $coursetags);
680d5c5b 198
e6890b11 199 $result['status'] = true;
680d5c5b
SL
200 }
201 }
202 }
203
204 return $result;
205 }
206
207 /**
208 * Returns description of method result value.
209 */
210 public static function submit_tags_form_returns() {
211 return new external_single_structure([
212 'status' => new external_value(PARAM_BOOL, 'status: true if success')
213 ]);
214 }
6768729e
RW
215
216 /**
217 * Returns description of method parameters.
218 *
219 * @return external_function_parameters.
220 */
221 public static function get_random_question_summaries_parameters() {
222 return new external_function_parameters([
223 'categoryid' => new external_value(PARAM_INT, 'Category id to find random questions'),
224 'includesubcategories' => new external_value(PARAM_BOOL, 'Include the subcategories in the search'),
225 'tagids' => new external_multiple_structure(
226 new external_value(PARAM_INT, 'Tag id')
227 ),
228 'contextid' => new external_value(PARAM_INT,
229 'Context id that the questions will be rendered in (used for exporting)'),
230 'limit' => new external_value(PARAM_INT, 'Maximum number of results to return',
231 VALUE_DEFAULT, 0),
232 'offset' => new external_value(PARAM_INT, 'Number of items to skip from the begging of the result set',
233 VALUE_DEFAULT, 0)
234 ]);
235 }
236
237 /**
238 * Gets the list of random questions for the given criteria. The questions
239 * will be exported in a summaries format and won't include all of the
240 * question data.
241 *
242 * @param int $categoryid Category id to find random questions
243 * @param bool $includesubcategories Include the subcategories in the search
244 * @param int[] $tagids Only include questions with these tags
245 * @param int $contextid The context id where the questions will be rendered
246 * @param int $limit Maximum number of results to return
247 * @param int $offset Number of items to skip from the beginning of the result set.
248 * @return array The list of questions and total question count.
249 */
250 public static function get_random_question_summaries(
251 $categoryid,
252 $includesubcategories,
253 $tagids,
254 $contextid,
255 $limit = 0,
256 $offset = 0
257 ) {
258 global $DB, $PAGE;
259
260 // Parameter validation.
261 $params = self::validate_parameters(
262 self::get_random_question_summaries_parameters(),
263 [
264 'categoryid' => $categoryid,
265 'includesubcategories' => $includesubcategories,
266 'tagids' => $tagids,
267 'contextid' => $contextid,
268 'limit' => $limit,
269 'offset' => $offset
270 ]
271 );
272 $categoryid = $params['categoryid'];
273 $includesubcategories = $params['includesubcategories'];
274 $tagids = $params['tagids'];
275 $contextid = $params['contextid'];
276 $limit = $params['limit'];
277 $offset = $params['offset'];
278
279 $context = \context::instance_by_id($contextid);
280 self::validate_context($context);
281
282 $categorycontextid = $DB->get_field('question_categories', 'contextid', ['id' => $categoryid], MUST_EXIST);
283 $categorycontext = \context::instance_by_id($categorycontextid);
284 $editcontexts = new \question_edit_contexts($categorycontext);
285 // The user must be able to view all questions in the category that they are requesting.
286 $editcontexts->require_cap('moodle/question:viewall');
287
288 $loader = new \core_question\bank\random_question_loader(new qubaid_list([]));
289 // Only load the properties we require from the DB.
290 $properties = \core_question\external\question_summary_exporter::get_mandatory_properties();
291 $questions = $loader->get_questions($categoryid, $includesubcategories, $tagids, $limit, $offset, $properties);
292 $totalcount = $loader->count_questions($categoryid, $includesubcategories, $tagids);
293 $renderer = $PAGE->get_renderer('core');
294
295 $formattedquestions = array_map(function($question) use ($context, $renderer) {
296 $exporter = new \core_question\external\question_summary_exporter($question, ['context' => $context]);
297 return $exporter->export($renderer);
298 }, $questions);
299
300 return [
301 'totalcount' => $totalcount,
302 'questions' => $formattedquestions
303 ];
304 }
305
306 /**
307 * Returns description of method result value.
308 */
309 public static function get_random_question_summaries_returns() {
310 return new external_single_structure([
311 'totalcount' => new external_value(PARAM_INT, 'total number of questions in result set'),
312 'questions' => new external_multiple_structure(
313 \core_question\external\question_summary_exporter::get_read_structure()
314 )
315 ]);
316 }
7361b968 317}