MDL-51929 external: Apply new validate_courses to data/lti/survey
[moodle.git] / mod / survey / classes / external.php
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/>.
17 /**
18  * Survey external API
19  *
20  * @package    mod_survey
21  * @category   external
22  * @copyright  2015 Juan Leyva <juan@moodle.com>
23  * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
24  * @since      Moodle 3.0
25  */
27 defined('MOODLE_INTERNAL') || die;
29 require_once($CFG->libdir . '/externallib.php');
30 require_once($CFG->dirroot . '/mod/survey/lib.php');
32 /**
33  * Survey external functions
34  *
35  * @package    mod_survey
36  * @category   external
37  * @copyright  2015 Juan Leyva <juan@moodle.com>
38  * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
39  * @since      Moodle 3.0
40  */
41 class mod_survey_external extends external_api {
43     /**
44      * Describes the parameters for get_surveys_by_courses.
45      *
46      * @return external_external_function_parameters
47      * @since Moodle 3.0
48      */
49     public static function get_surveys_by_courses_parameters() {
50         return new external_function_parameters (
51             array(
52                 'courseids' => new external_multiple_structure(
53                     new external_value(PARAM_INT, 'course id'), 'Array of course ids', VALUE_DEFAULT, array()
54                 ),
55             )
56         );
57     }
59     /**
60      * Returns a list of surveys in a provided list of courses,
61      * if no list is provided all surveys that the user can view will be returned.
62      *
63      * @param array $courseids the course ids
64      * @return array of surveys details
65      * @since Moodle 3.0
66      */
67     public static function get_surveys_by_courses($courseids = array()) {
68         global $CFG, $USER, $DB;
70         $returnedsurveys = array();
71         $warnings = array();
73         $params = self::validate_parameters(self::get_surveys_by_courses_parameters(), array('courseids' => $courseids));
75         $mycourses = array();
76         if (empty($params['courseids'])) {
77             $mycourses = enrol_get_my_courses();
78             $params['courseids'] = array_keys($mycourses);
79         }
81         // Ensure there are courseids to loop through.
82         if (!empty($params['courseids'])) {
84             list($courses, $warnings) = external_util::validate_courses($params['courseids'], $mycourses);
86             // Get the surveys in this course, this function checks users visibility permissions.
87             // We can avoid then additional validate_context calls.
88             $surveys = get_all_instances_in_courses("survey", $courses);
89             foreach ($surveys as $survey) {
90                 $context = context_module::instance($survey->coursemodule);
91                 // Entry to return.
92                 $surveydetails = array();
93                 // First, we return information that any user can see in the web interface.
94                 $surveydetails['id'] = $survey->id;
95                 $surveydetails['coursemodule']      = $survey->coursemodule;
96                 $surveydetails['course']            = $survey->course;
97                 $surveydetails['name']              = external_format_string($survey->name, $context->id);
99                 if (has_capability('mod/survey:participate', $context)) {
100                     $trimmedintro = trim($survey->intro);
101                     if (empty($trimmedintro)) {
102                         $tempo = $DB->get_field("survey", "intro", array("id" => $survey->template));
103                         $survey->intro = get_string($tempo, "survey");
104                     }
106                     // Format intro.
107                     list($surveydetails['intro'], $surveydetails['introformat']) =
108                         external_format_text($survey->intro, $survey->introformat, $context->id, 'mod_survey', 'intro', null);
110                     $surveydetails['template']  = $survey->template;
111                     $surveydetails['days']      = $survey->days;
112                     $surveydetails['questions'] = $survey->questions;
113                     $surveydetails['surveydone'] = survey_already_done($survey->id, $USER->id) ? 1 : 0;
115                 }
117                 if (has_capability('moodle/course:manageactivities', $context)) {
118                     $surveydetails['timecreated']   = $survey->timecreated;
119                     $surveydetails['timemodified']  = $survey->timemodified;
120                     $surveydetails['section']       = $survey->section;
121                     $surveydetails['visible']       = $survey->visible;
122                     $surveydetails['groupmode']     = $survey->groupmode;
123                     $surveydetails['groupingid']    = $survey->groupingid;
124                 }
125                 $returnedsurveys[] = $surveydetails;
126             }
127         }
128         $result = array();
129         $result['surveys'] = $returnedsurveys;
130         $result['warnings'] = $warnings;
131         return $result;
132     }
134     /**
135      * Describes the get_surveys_by_courses return value.
136      *
137      * @return external_single_structure
138      * @since Moodle 3.0
139      */
140     public static function get_surveys_by_courses_returns() {
141         return new external_single_structure(
142             array(
143                 'surveys' => new external_multiple_structure(
144                     new external_single_structure(
145                         array(
146                             'id' => new external_value(PARAM_INT, 'Survey id'),
147                             'coursemodule' => new external_value(PARAM_INT, 'Course module id'),
148                             'course' => new external_value(PARAM_INT, 'Course id'),
149                             'name' => new external_value(PARAM_RAW, 'Survey name'),
150                             'intro' => new external_value(PARAM_RAW, 'The Survey intro', VALUE_OPTIONAL),
151                             'introformat' => new external_format_value('intro', VALUE_OPTIONAL),
152                             'template' => new external_value(PARAM_INT, 'Survey type', VALUE_OPTIONAL),
153                             'days' => new external_value(PARAM_INT, 'Days', VALUE_OPTIONAL),
154                             'questions' => new external_value(PARAM_RAW, 'Question ids', VALUE_OPTIONAL),
155                             'surveydone' => new external_value(PARAM_INT, 'Did I finish the survey?', VALUE_OPTIONAL),
156                             'timecreated' => new external_value(PARAM_INT, 'Time of creation', VALUE_OPTIONAL),
157                             'timemodified' => new external_value(PARAM_INT, 'Time of last modification', VALUE_OPTIONAL),
158                             'section' => new external_value(PARAM_INT, 'Course section id', VALUE_OPTIONAL),
159                             'visible' => new external_value(PARAM_INT, 'Visible', VALUE_OPTIONAL),
160                             'groupmode' => new external_value(PARAM_INT, 'Group mode', VALUE_OPTIONAL),
161                             'groupingid' => new external_value(PARAM_INT, 'Group id', VALUE_OPTIONAL),
162                         ), 'Surveys'
163                     )
164                 ),
165                 'warnings' => new external_warnings(),
166             )
167         );
168     }
170     /**
171      * Returns description of method parameters
172      *
173      * @return external_function_parameters
174      * @since Moodle 3.0
175      */
176     public static function view_survey_parameters() {
177         return new external_function_parameters(
178             array(
179                 'surveyid' => new external_value(PARAM_INT, 'survey instance id')
180             )
181         );
182     }
184     /**
185      * Trigger the course module viewed event and update the module completion status.
186      *
187      * @param int $surveyid the survey instance id
188      * @return array of warnings and status result
189      * @since Moodle 3.0
190      * @throws moodle_exception
191      */
192     public static function view_survey($surveyid) {
193         global $DB, $USER;
195         $params = self::validate_parameters(self::view_survey_parameters(),
196                                             array(
197                                                 'surveyid' => $surveyid
198                                             ));
199         $warnings = array();
201         // Request and permission validation.
202         $survey = $DB->get_record('survey', array('id' => $params['surveyid']), '*', MUST_EXIST);
203         list($course, $cm) = get_course_and_cm_from_instance($survey, 'survey');
205         $context = context_module::instance($cm->id);
206         self::validate_context($context);
207         require_capability('mod/survey:participate', $context);
209         $viewed = survey_already_done($survey->id, $USER->id) ? 'graph' : 'form';
211         // Trigger course_module_viewed event and completion.
212         survey_view($survey, $course, $cm, $context, $viewed);
214         $result = array();
215         $result['status'] = true;
216         $result['warnings'] = $warnings;
217         return $result;
218     }
220     /**
221      * Returns description of method result value
222      *
223      * @return external_description
224      * @since Moodle 3.0
225      */
226     public static function view_survey_returns() {
227         return new external_single_structure(
228             array(
229                 'status' => new external_value(PARAM_BOOL, 'status: true if success'),
230                 'warnings' => new external_warnings()
231             )
232         );
233     }
235     /**
236      * Returns description of method parameters
237      *
238      * @return external_function_parameters
239      * @since Moodle 3.0
240      */
241     public static function get_questions_parameters() {
242         return new external_function_parameters(
243             array(
244                 'surveyid' => new external_value(PARAM_INT, 'survey instance id')
245             )
246         );
247     }
249     /**
250      * Get the complete list of questions for the survey, including subquestions.
251      *
252      * @param int $surveyid the survey instance id
253      * @return array of warnings and the question list
254      * @since Moodle 3.0
255      * @throws moodle_exception
256      */
257     public static function get_questions($surveyid) {
258         global $DB, $USER;
260         $params = self::validate_parameters(self::get_questions_parameters(),
261                                             array(
262                                                 'surveyid' => $surveyid
263                                             ));
264         $warnings = array();
266         // Request and permission validation.
267         $survey = $DB->get_record('survey', array('id' => $params['surveyid']), '*', MUST_EXIST);
268         list($course, $cm) = get_course_and_cm_from_instance($survey, 'survey');
270         $context = context_module::instance($cm->id);
271         self::validate_context($context);
272         require_capability('mod/survey:participate', $context);
274         $mainquestions = survey_get_questions($survey);
276         foreach ($mainquestions as $question) {
277             if ($question->type >= 0) {
278                 // Parent is used in subquestions.
279                 $question->parent = 0;
280                 $questions[] = survey_translate_question($question);
282                 // Check if the question has subquestions.
283                 if ($question->multi) {
284                     $subquestions = survey_get_subquestions($question);
285                     foreach ($subquestions as $sq) {
286                         $sq->parent = $question->id;
287                         $questions[] = survey_translate_question($sq);
288                     }
289                 }
290             }
291         }
293         $result = array();
294         $result['questions'] = $questions;
295         $result['warnings'] = $warnings;
296         return $result;
297     }
299     /**
300      * Returns description of method result value
301      *
302      * @return external_description
303      * @since Moodle 3.0
304      */
305     public static function get_questions_returns() {
306         return new external_single_structure(
307             array(
308                 'questions' => new external_multiple_structure(
309                     new external_single_structure(
310                         array(
311                             'id' => new external_value(PARAM_INT, 'Question id'),
312                             'text' => new external_value(PARAM_RAW, 'Question text'),
313                             'shorttext' => new external_value(PARAM_RAW, 'Question short text'),
314                             'multi' => new external_value(PARAM_RAW, 'Subquestions ids'),
315                             'intro' => new external_value(PARAM_RAW, 'The question intro'),
316                             'type' => new external_value(PARAM_INT, 'Question type'),
317                             'options' => new external_value(PARAM_RAW, 'Question options'),
318                             'parent' => new external_value(PARAM_INT, 'Parent question (for subquestions)'),
319                         ), 'Questions'
320                     )
321                 ),
322                 'warnings' => new external_warnings()
323             )
324         );
325     }
327     /**
328      * Describes the parameters for submit_answers.
329      *
330      * @return external_function_parameters
331      * @since Moodle 3.0
332      */
333     public static function submit_answers_parameters() {
334         return new external_function_parameters(
335             array(
336                 'surveyid' => new external_value(PARAM_INT, 'Survey id'),
337                 'answers' => new external_multiple_structure(
338                     new external_single_structure(
339                         array(
340                             'key' => new external_value(PARAM_RAW, 'Answer key'),
341                             'value' => new external_value(PARAM_RAW, 'Answer value')
342                         )
343                     )
344                 ),
345             )
346         );
347     }
349     /**
350      * Submit the answers for a given survey.
351      *
352      * @param int $surveyid the survey instance id
353      * @param array $answers the survey answers
354      * @return array of warnings and status result
355      * @since Moodle 3.0
356      * @throws moodle_exception
357      */
358     public static function submit_answers($surveyid, $answers) {
359         global $DB, $USER;
361         $params = self::validate_parameters(self::submit_answers_parameters(),
362                                             array(
363                                                 'surveyid' => $surveyid,
364                                                 'answers' => $answers
365                                             ));
366         $warnings = array();
368         // Request and permission validation.
369         $survey = $DB->get_record('survey', array('id' => $params['surveyid']), '*', MUST_EXIST);
370         list($course, $cm) = get_course_and_cm_from_instance($survey, 'survey');
372         $context = context_module::instance($cm->id);
373         self::validate_context($context);
374         require_capability('mod/survey:participate', $context);
376         if (survey_already_done($survey->id, $USER->id)) {
377             throw new moodle_exception("alreadysubmitted", "survey");
378         }
380         // Build the answers array. Data is cleaned inside the survey_save_answers function.
381         $answers = array();
382         foreach ($params['answers'] as $answer) {
383             $key = $answer['key'];
384             $answers[$key] = $answer['value'];
385         }
387         survey_save_answers($survey, $answers, $course, $context);
389         $result = array();
390         $result['status'] = true;
391         $result['warnings'] = $warnings;
392         return $result;
393     }
395     /**
396      * Returns description of method result value
397      *
398      * @return external_description
399      * @since Moodle 3.0
400      */
401     public static function submit_answers_returns() {
402         return new external_single_structure(
403             array(
404                 'status' => new external_value(PARAM_BOOL, 'status: true if success'),
405                 'warnings' => new external_warnings()
406             )
407         );
408     }