7302bfe3a6736f76d0ceea36c110950d97fe52e6
[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         if (empty($params['courseids'])) {
76             $params['courseids'] = array_keys(enrol_get_my_courses());
77         }
79         // Ensure there are courseids to loop through.
80         if (!empty($params['courseids'])) {
82             list($courses, $warnings) = external_util::validate_courses($params['courseids']);
84             // Get the surveys in this course, this function checks users visibility permissions.
85             // We can avoid then additional validate_context calls.
86             $surveys = get_all_instances_in_courses("survey", $courses);
87             foreach ($surveys as $survey) {
88                 $context = context_module::instance($survey->coursemodule);
89                 // Entry to return.
90                 $surveydetails = array();
91                 // First, we return information that any user can see in the web interface.
92                 $surveydetails['id'] = $survey->id;
93                 $surveydetails['coursemodule']      = $survey->coursemodule;
94                 $surveydetails['course']            = $survey->course;
95                 $surveydetails['name']              = external_format_string($survey->name, $context->id);
97                 if (has_capability('mod/survey:participate', $context)) {
98                     $trimmedintro = trim($survey->intro);
99                     if (empty($trimmedintro)) {
100                         $tempo = $DB->get_field("survey", "intro", array("id" => $survey->template));
101                         $survey->intro = get_string($tempo, "survey");
102                     }
104                     // Format intro.
105                     list($surveydetails['intro'], $surveydetails['introformat']) =
106                         external_format_text($survey->intro, $survey->introformat, $context->id, 'mod_survey', 'intro', null);
108                     $surveydetails['template']  = $survey->template;
109                     $surveydetails['days']      = $survey->days;
110                     $surveydetails['questions'] = $survey->questions;
111                     $surveydetails['surveydone'] = survey_already_done($survey->id, $USER->id) ? 1 : 0;
113                 }
115                 if (has_capability('moodle/course:manageactivities', $context)) {
116                     $surveydetails['timecreated']   = $survey->timecreated;
117                     $surveydetails['timemodified']  = $survey->timemodified;
118                     $surveydetails['section']       = $survey->section;
119                     $surveydetails['visible']       = $survey->visible;
120                     $surveydetails['groupmode']     = $survey->groupmode;
121                     $surveydetails['groupingid']    = $survey->groupingid;
122                 }
123                 $returnedsurveys[] = $surveydetails;
124             }
125         }
126         $result = array();
127         $result['surveys'] = $returnedsurveys;
128         $result['warnings'] = $warnings;
129         return $result;
130     }
132     /**
133      * Describes the get_surveys_by_courses return value.
134      *
135      * @return external_single_structure
136      * @since Moodle 3.0
137      */
138     public static function get_surveys_by_courses_returns() {
139         return new external_single_structure(
140             array(
141                 'surveys' => new external_multiple_structure(
142                     new external_single_structure(
143                         array(
144                             'id' => new external_value(PARAM_INT, 'Survey id'),
145                             'coursemodule' => new external_value(PARAM_INT, 'Course module id'),
146                             'course' => new external_value(PARAM_INT, 'Course id'),
147                             'name' => new external_value(PARAM_RAW, 'Survey name'),
148                             'intro' => new external_value(PARAM_RAW, 'The Survey intro', VALUE_OPTIONAL),
149                             'introformat' => new external_format_value('intro', VALUE_OPTIONAL),
150                             'template' => new external_value(PARAM_INT, 'Survey type', VALUE_OPTIONAL),
151                             'days' => new external_value(PARAM_INT, 'Days', VALUE_OPTIONAL),
152                             'questions' => new external_value(PARAM_RAW, 'Question ids', VALUE_OPTIONAL),
153                             'surveydone' => new external_value(PARAM_INT, 'Did I finish the survey?', VALUE_OPTIONAL),
154                             'timecreated' => new external_value(PARAM_INT, 'Time of creation', VALUE_OPTIONAL),
155                             'timemodified' => new external_value(PARAM_INT, 'Time of last modification', VALUE_OPTIONAL),
156                             'section' => new external_value(PARAM_INT, 'Course section id', VALUE_OPTIONAL),
157                             'visible' => new external_value(PARAM_INT, 'Visible', VALUE_OPTIONAL),
158                             'groupmode' => new external_value(PARAM_INT, 'Group mode', VALUE_OPTIONAL),
159                             'groupingid' => new external_value(PARAM_INT, 'Group id', VALUE_OPTIONAL),
160                         ), 'Surveys'
161                     )
162                 ),
163                 'warnings' => new external_warnings(),
164             )
165         );
166     }
168     /**
169      * Returns description of method parameters
170      *
171      * @return external_function_parameters
172      * @since Moodle 3.0
173      */
174     public static function view_survey_parameters() {
175         return new external_function_parameters(
176             array(
177                 'surveyid' => new external_value(PARAM_INT, 'survey instance id')
178             )
179         );
180     }
182     /**
183      * Trigger the course module viewed event and update the module completion status.
184      *
185      * @param int $surveyid the survey instance id
186      * @return array of warnings and status result
187      * @since Moodle 3.0
188      * @throws moodle_exception
189      */
190     public static function view_survey($surveyid) {
191         global $DB, $USER;
193         $params = self::validate_parameters(self::view_survey_parameters(),
194                                             array(
195                                                 'surveyid' => $surveyid
196                                             ));
197         $warnings = array();
199         // Request and permission validation.
200         $survey = $DB->get_record('survey', array('id' => $params['surveyid']), '*', MUST_EXIST);
201         list($course, $cm) = get_course_and_cm_from_instance($survey, 'survey');
203         $context = context_module::instance($cm->id);
204         self::validate_context($context);
205         require_capability('mod/survey:participate', $context);
207         $viewed = survey_already_done($survey->id, $USER->id) ? 'graph' : 'form';
209         // Trigger course_module_viewed event and completion.
210         survey_view($survey, $course, $cm, $context, $viewed);
212         $result = array();
213         $result['status'] = true;
214         $result['warnings'] = $warnings;
215         return $result;
216     }
218     /**
219      * Returns description of method result value
220      *
221      * @return external_description
222      * @since Moodle 3.0
223      */
224     public static function view_survey_returns() {
225         return new external_single_structure(
226             array(
227                 'status' => new external_value(PARAM_BOOL, 'status: true if success'),
228                 'warnings' => new external_warnings()
229             )
230         );
231     }
233     /**
234      * Returns description of method parameters
235      *
236      * @return external_function_parameters
237      * @since Moodle 3.0
238      */
239     public static function get_questions_parameters() {
240         return new external_function_parameters(
241             array(
242                 'surveyid' => new external_value(PARAM_INT, 'survey instance id')
243             )
244         );
245     }
247     /**
248      * Get the complete list of questions for the survey, including subquestions.
249      *
250      * @param int $surveyid the survey instance id
251      * @return array of warnings and the question list
252      * @since Moodle 3.0
253      * @throws moodle_exception
254      */
255     public static function get_questions($surveyid) {
256         global $DB, $USER;
258         $params = self::validate_parameters(self::get_questions_parameters(),
259                                             array(
260                                                 'surveyid' => $surveyid
261                                             ));
262         $warnings = array();
264         // Request and permission validation.
265         $survey = $DB->get_record('survey', array('id' => $params['surveyid']), '*', MUST_EXIST);
266         list($course, $cm) = get_course_and_cm_from_instance($survey, 'survey');
268         $context = context_module::instance($cm->id);
269         self::validate_context($context);
270         require_capability('mod/survey:participate', $context);
272         $mainquestions = survey_get_questions($survey);
274         foreach ($mainquestions as $question) {
275             if ($question->type >= 0) {
276                 // Parent is used in subquestions.
277                 $question->parent = 0;
278                 $questions[] = survey_translate_question($question);
280                 // Check if the question has subquestions.
281                 if ($question->multi) {
282                     $subquestions = survey_get_subquestions($question);
283                     foreach ($subquestions as $sq) {
284                         $sq->parent = $question->id;
285                         $questions[] = survey_translate_question($sq);
286                     }
287                 }
288             }
289         }
291         $result = array();
292         $result['questions'] = $questions;
293         $result['warnings'] = $warnings;
294         return $result;
295     }
297     /**
298      * Returns description of method result value
299      *
300      * @return external_description
301      * @since Moodle 3.0
302      */
303     public static function get_questions_returns() {
304         return new external_single_structure(
305             array(
306                 'questions' => new external_multiple_structure(
307                     new external_single_structure(
308                         array(
309                             'id' => new external_value(PARAM_INT, 'Question id'),
310                             'text' => new external_value(PARAM_RAW, 'Question text'),
311                             'shorttext' => new external_value(PARAM_RAW, 'Question short text'),
312                             'multi' => new external_value(PARAM_RAW, 'Subquestions ids'),
313                             'intro' => new external_value(PARAM_RAW, 'The question intro'),
314                             'type' => new external_value(PARAM_INT, 'Question type'),
315                             'options' => new external_value(PARAM_RAW, 'Question options'),
316                             'parent' => new external_value(PARAM_INT, 'Parent question (for subquestions)'),
317                         ), 'Questions'
318                     )
319                 ),
320                 'warnings' => new external_warnings()
321             )
322         );
323     }
325     /**
326      * Describes the parameters for submit_answers.
327      *
328      * @return external_function_parameters
329      * @since Moodle 3.0
330      */
331     public static function submit_answers_parameters() {
332         return new external_function_parameters(
333             array(
334                 'surveyid' => new external_value(PARAM_INT, 'Survey id'),
335                 'answers' => new external_multiple_structure(
336                     new external_single_structure(
337                         array(
338                             'key' => new external_value(PARAM_RAW, 'Answer key'),
339                             'value' => new external_value(PARAM_RAW, 'Answer value')
340                         )
341                     )
342                 ),
343             )
344         );
345     }
347     /**
348      * Submit the answers for a given survey.
349      *
350      * @param int $surveyid the survey instance id
351      * @param array $answers the survey answers
352      * @return array of warnings and status result
353      * @since Moodle 3.0
354      * @throws moodle_exception
355      */
356     public static function submit_answers($surveyid, $answers) {
357         global $DB, $USER;
359         $params = self::validate_parameters(self::submit_answers_parameters(),
360                                             array(
361                                                 'surveyid' => $surveyid,
362                                                 'answers' => $answers
363                                             ));
364         $warnings = array();
366         // Request and permission validation.
367         $survey = $DB->get_record('survey', array('id' => $params['surveyid']), '*', MUST_EXIST);
368         list($course, $cm) = get_course_and_cm_from_instance($survey, 'survey');
370         $context = context_module::instance($cm->id);
371         self::validate_context($context);
372         require_capability('mod/survey:participate', $context);
374         if (survey_already_done($survey->id, $USER->id)) {
375             throw new moodle_exception("alreadysubmitted", "survey");
376         }
378         // Build the answers array. Data is cleaned inside the survey_save_answers function.
379         $answers = array();
380         foreach ($params['answers'] as $answer) {
381             $key = $answer['key'];
382             $answers[$key] = $answer['value'];
383         }
385         survey_save_answers($survey, $answers, $course, $context);
387         $result = array();
388         $result['status'] = true;
389         $result['warnings'] = $warnings;
390         return $result;
391     }
393     /**
394      * Returns description of method result value
395      *
396      * @return external_description
397      * @since Moodle 3.0
398      */
399     public static function submit_answers_returns() {
400         return new external_single_structure(
401             array(
402                 'status' => new external_value(PARAM_BOOL, 'status: true if success'),
403                 'warnings' => new external_warnings()
404             )
405         );
406     }