Merge branch 'MDL-50937-master' of git://github.com/damyon/moodle
[moodle.git] / mod / assign / externallib.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  * External assign API
19  *
20  * @package    mod_assign
21  * @since      Moodle 2.4
22  * @copyright  2012 Paul Charsley
23  * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
24  */
26 defined('MOODLE_INTERNAL') || die;
28 require_once("$CFG->libdir/externallib.php");
29 require_once("$CFG->dirroot/user/externallib.php");
30 require_once("$CFG->dirroot/mod/assign/locallib.php");
32 /**
33  * Assign functions
34  * @copyright 2012 Paul Charsley
35  * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
36  */
37 class mod_assign_external extends external_api {
39     /**
40      * Generate a warning in a standard structure for a known failure.
41      *
42      * @param int $assignmentid - The assignment
43      * @param string $warningcode - The key for the warning message
44      * @param string $detail - A description of the error
45      * @return array - Warning structure containing item, itemid, warningcode, message
46      */
47     private static function generate_warning($assignmentid, $warningcode, $detail) {
48         $warningmessages = array(
49             'couldnotlock'=>'Could not lock the submission for this user.',
50             'couldnotunlock'=>'Could not unlock the submission for this user.',
51             'couldnotsubmitforgrading'=>'Could not submit assignment for grading.',
52             'couldnotrevealidentities'=>'Could not reveal identities.',
53             'couldnotgrantextensions'=>'Could not grant submission date extensions.',
54             'couldnotrevert'=>'Could not revert submission to draft.',
55             'invalidparameters'=>'Invalid parameters.',
56             'couldnotsavesubmission'=>'Could not save submission.',
57             'couldnotsavegrade'=>'Could not save grade.'
58         );
60         $message = $warningmessages[$warningcode];
61         if (empty($message)) {
62             $message = 'Unknown warning type.';
63         }
65         return array('item'=>$detail,
66                      'itemid'=>$assignmentid,
67                      'warningcode'=>$warningcode,
68                      'message'=>$message);
69     }
71     /**
72      * Describes the parameters for get_grades
73      * @return external_external_function_parameters
74      * @since  Moodle 2.4
75      */
76     public static function get_grades_parameters() {
77         return new external_function_parameters(
78             array(
79                 'assignmentids' => new external_multiple_structure(
80                     new external_value(PARAM_INT, 'assignment id'),
81                     '1 or more assignment ids',
82                     VALUE_REQUIRED),
83                 'since' => new external_value(PARAM_INT,
84                           'timestamp, only return records where timemodified >= since',
85                           VALUE_DEFAULT, 0)
86             )
87         );
88     }
90     /**
91      * Returns grade information from assign_grades for the requested assignment ids
92      * @param int[] $assignmentids
93      * @param int $since only return records with timemodified >= since
94      * @return array of grade records for each requested assignment
95      * @since  Moodle 2.4
96      */
97     public static function get_grades($assignmentids, $since = 0) {
98         global $DB;
99         $params = self::validate_parameters(self::get_grades_parameters(),
100                         array('assignmentids' => $assignmentids,
101                               'since' => $since));
103         $assignments = array();
104         $warnings = array();
105         $requestedassignmentids = $params['assignmentids'];
107         // Check the user is allowed to get the grades for the assignments requested.
108         $placeholders = array();
109         list($sqlassignmentids, $placeholders) = $DB->get_in_or_equal($requestedassignmentids, SQL_PARAMS_NAMED);
110         $sql = "SELECT cm.id, cm.instance FROM {course_modules} cm JOIN {modules} md ON md.id = cm.module ".
111                "WHERE md.name = :modname AND cm.instance ".$sqlassignmentids;
112         $placeholders['modname'] = 'assign';
113         $cms = $DB->get_records_sql($sql, $placeholders);
114         foreach ($cms as $cm) {
115             try {
116                 $context = context_module::instance($cm->id);
117                 self::validate_context($context);
118                 require_capability('mod/assign:grade', $context);
119             } catch (Exception $e) {
120                 $requestedassignmentids = array_diff($requestedassignmentids, array($cm->instance));
121                 $warning = array();
122                 $warning['item'] = 'assignment';
123                 $warning['itemid'] = $cm->instance;
124                 $warning['warningcode'] = '1';
125                 $warning['message'] = 'No access rights in module context';
126                 $warnings[] = $warning;
127             }
128         }
130         // Create the query and populate an array of grade records from the recordset results.
131         if (count ($requestedassignmentids) > 0) {
132             $placeholders = array();
133             list($inorequalsql, $placeholders) = $DB->get_in_or_equal($requestedassignmentids, SQL_PARAMS_NAMED);
135             $sql = "SELECT ag.id,
136                            ag.assignment,
137                            ag.userid,
138                            ag.timecreated,
139                            ag.timemodified,
140                            ag.grader,
141                            ag.grade,
142                            ag.attemptnumber
143                       FROM {assign_grades} ag, {assign_submission} s
144                      WHERE s.assignment $inorequalsql
145                        AND s.userid = ag.userid
146                        AND s.latest = 1
147                        AND s.attemptnumber = ag.attemptnumber
148                        AND ag.timemodified  >= :since
149                        AND ag.assignment = s.assignment
150                   ORDER BY ag.assignment, ag.id";
152             $placeholders['since'] = $params['since'];
153             $rs = $DB->get_recordset_sql($sql, $placeholders);
154             $currentassignmentid = null;
155             $assignment = null;
156             foreach ($rs as $rd) {
157                 $grade = array();
158                 $grade['id'] = $rd->id;
159                 $grade['userid'] = $rd->userid;
160                 $grade['timecreated'] = $rd->timecreated;
161                 $grade['timemodified'] = $rd->timemodified;
162                 $grade['grader'] = $rd->grader;
163                 $grade['attemptnumber'] = $rd->attemptnumber;
164                 $grade['grade'] = (string)$rd->grade;
166                 if (is_null($currentassignmentid) || ($rd->assignment != $currentassignmentid )) {
167                     if (!is_null($assignment)) {
168                         $assignments[] = $assignment;
169                     }
170                     $assignment = array();
171                     $assignment['assignmentid'] = $rd->assignment;
172                     $assignment['grades'] = array();
173                     $requestedassignmentids = array_diff($requestedassignmentids, array($rd->assignment));
174                 }
175                 $assignment['grades'][] = $grade;
177                 $currentassignmentid = $rd->assignment;
178             }
179             if (!is_null($assignment)) {
180                 $assignments[] = $assignment;
181             }
182             $rs->close();
183         }
184         foreach ($requestedassignmentids as $assignmentid) {
185             $warning = array();
186             $warning['item'] = 'assignment';
187             $warning['itemid'] = $assignmentid;
188             $warning['warningcode'] = '3';
189             $warning['message'] = 'No grades found';
190             $warnings[] = $warning;
191         }
193         $result = array();
194         $result['assignments'] = $assignments;
195         $result['warnings'] = $warnings;
196         return $result;
197     }
199     /**
200      * Creates a grade single structure.
201      *
202      * @return external_single_structure a grade single structure.
203      * @since  Moodle 3.1
204      */
205     private static function get_grade_structure($required = VALUE_REQUIRED) {
206         return new external_single_structure(
207             array(
208                 'id'                => new external_value(PARAM_INT, 'grade id'),
209                 'assignment'        => new external_value(PARAM_INT, 'assignment id', VALUE_OPTIONAL),
210                 'userid'            => new external_value(PARAM_INT, 'student id'),
211                 'attemptnumber'     => new external_value(PARAM_INT, 'attempt number'),
212                 'timecreated'       => new external_value(PARAM_INT, 'grade creation time'),
213                 'timemodified'      => new external_value(PARAM_INT, 'grade last modified time'),
214                 'grader'            => new external_value(PARAM_INT, 'grader'),
215                 'grade'             => new external_value(PARAM_TEXT, 'grade'),
216                 'gradefordisplay'   => new external_value(PARAM_RAW, 'grade rendered into a format suitable for display',
217                                                             VALUE_OPTIONAL),
218             ), 'grade information', $required
219         );
220     }
222     /**
223      * Creates an assign_grades external_single_structure
224      * @return external_single_structure
225      * @since  Moodle 2.4
226      */
227     private static function assign_grades() {
228         return new external_single_structure(
229             array (
230                 'assignmentid'  => new external_value(PARAM_INT, 'assignment id'),
231                 'grades'        => new external_multiple_structure(self::get_grade_structure())
232             )
233         );
234     }
236     /**
237      * Describes the get_grades return value
238      * @return external_single_structure
239      * @since  Moodle 2.4
240      */
241     public static function get_grades_returns() {
242         return new external_single_structure(
243             array(
244                 'assignments' => new external_multiple_structure(self::assign_grades(), 'list of assignment grade information'),
245                 'warnings'      => new external_warnings('item is always \'assignment\'',
246                     'when errorcode is 3 then itemid is an assignment id. When errorcode is 1, itemid is a course module id',
247                     'errorcode can be 3 (no grades found) or 1 (no permission to get grades)')
248             )
249         );
250     }
252     /**
253      * Returns description of method parameters
254      *
255      * @return external_function_parameters
256      * @since  Moodle 2.4
257      */
258     public static function get_assignments_parameters() {
259         return new external_function_parameters(
260             array(
261                 'courseids' => new external_multiple_structure(
262                     new external_value(PARAM_INT, 'course id, empty for retrieving all the courses where the user is enroled in'),
263                     '0 or more course ids',
264                     VALUE_DEFAULT, array()
265                 ),
266                 'capabilities'  => new external_multiple_structure(
267                     new external_value(PARAM_CAPABILITY, 'capability'),
268                     'list of capabilities used to filter courses',
269                     VALUE_DEFAULT, array()
270                 ),
271                 'includenotenrolledcourses' => new external_value(PARAM_BOOL, 'whether to return courses that the user can see
272                                                                     even if is not enroled in. This requires the parameter courseids
273                                                                     to not be empty.', VALUE_DEFAULT, false)
274             )
275         );
276     }
278     /**
279      * Returns an array of courses the user is enrolled, and for each course all of the assignments that the user can
280      * view within that course.
281      *
282      * @param array $courseids An optional array of course ids. If provided only assignments within the given course
283      * will be returned. If the user is not enrolled in or can't view a given course a warning will be generated and returned.
284      * @param array $capabilities An array of additional capability checks you wish to be made on the course context.
285      * @param bool $includenotenrolledcourses Wheter to return courses that the user can see even if is not enroled in.
286      * This requires the parameter $courseids to not be empty.
287      * @return An array of courses and warnings.
288      * @since  Moodle 2.4
289      */
290     public static function get_assignments($courseids = array(), $capabilities = array(), $includenotenrolledcourses = false) {
291         global $USER, $DB, $CFG;
293         $params = self::validate_parameters(
294             self::get_assignments_parameters(),
295             array(
296                 'courseids' => $courseids,
297                 'capabilities' => $capabilities,
298                 'includenotenrolledcourses' => $includenotenrolledcourses
299             )
300         );
302         $warnings = array();
303         $courses = array();
304         $fields = 'sortorder,shortname,fullname,timemodified';
306         // If the courseids list is empty, we return only the courses where the user is enrolled in.
307         if (empty($params['courseids'])) {
308             $courses = enrol_get_users_courses($USER->id, true, $fields);
309             $courseids = array_keys($courses);
310         } else if ($includenotenrolledcourses) {
311             // In this case, we don't have to check here for enrolmnents. Maybe the user can see the course even if is not enrolled.
312             $courseids = $params['courseids'];
313         } else {
314             // We need to check for enrolments.
315             $mycourses = enrol_get_users_courses($USER->id, true, $fields);
316             $mycourseids = array_keys($mycourses);
318             foreach ($params['courseids'] as $courseid) {
319                 if (!in_array($courseid, $mycourseids)) {
320                     unset($courses[$courseid]);
321                     $warnings[] = array(
322                         'item' => 'course',
323                         'itemid' => $courseid,
324                         'warningcode' => '2',
325                         'message' => 'User is not enrolled or does not have requested capability'
326                     );
327                 } else {
328                     $courses[$courseid] = $mycourses[$courseid];
329                 }
330             }
331             $courseids = array_keys($courses);
332         }
334         foreach ($courseids as $cid) {
336             try {
337                 $context = context_course::instance($cid);
338                 self::validate_context($context);
340                 // Check if this course was already loaded (by enrol_get_users_courses).
341                 if (!isset($courses[$cid])) {
342                     $courses[$cid] = get_course($cid);
343                 }
344                 $courses[$cid]->contextid = $context->id;
345             } catch (Exception $e) {
346                 unset($courses[$cid]);
347                 $warnings[] = array(
348                     'item' => 'course',
349                     'itemid' => $cid,
350                     'warningcode' => '1',
351                     'message' => 'No access rights in course context '.$e->getMessage()
352                 );
353                 continue;
354             }
355             if (count($params['capabilities']) > 0 && !has_all_capabilities($params['capabilities'], $context)) {
356                 unset($courses[$cid]);
357             }
358         }
359         $extrafields='m.id as assignmentid, ' .
360                      'm.course, ' .
361                      'm.nosubmissions, ' .
362                      'm.submissiondrafts, ' .
363                      'm.sendnotifications, '.
364                      'm.sendlatenotifications, ' .
365                      'm.sendstudentnotifications, ' .
366                      'm.duedate, ' .
367                      'm.allowsubmissionsfromdate, '.
368                      'm.grade, ' .
369                      'm.timemodified, '.
370                      'm.completionsubmit, ' .
371                      'm.cutoffdate, ' .
372                      'm.teamsubmission, ' .
373                      'm.requireallteammemberssubmit, '.
374                      'm.teamsubmissiongroupingid, ' .
375                      'm.blindmarking, ' .
376                      'm.revealidentities, ' .
377                      'm.attemptreopenmethod, '.
378                      'm.maxattempts, ' .
379                      'm.markingworkflow, ' .
380                      'm.markingallocation, ' .
381                      'm.requiresubmissionstatement, '.
382                      'm.preventsubmissionnotingroup, '.
383                      'm.intro, '.
384                      'm.introformat';
385         $coursearray = array();
386         foreach ($courses as $id => $course) {
387             $assignmentarray = array();
388             // Get a list of assignments for the course.
389             if ($modules = get_coursemodules_in_course('assign', $courses[$id]->id, $extrafields)) {
390                 foreach ($modules as $module) {
391                     $context = context_module::instance($module->id);
392                     try {
393                         self::validate_context($context);
394                         require_capability('mod/assign:view', $context);
395                     } catch (Exception $e) {
396                         $warnings[] = array(
397                             'item' => 'module',
398                             'itemid' => $module->id,
399                             'warningcode' => '1',
400                             'message' => 'No access rights in module context'
401                         );
402                         continue;
403                     }
404                     $configrecords = $DB->get_recordset('assign_plugin_config', array('assignment' => $module->assignmentid));
405                     $configarray = array();
406                     foreach ($configrecords as $configrecord) {
407                         $configarray[] = array(
408                             'id' => $configrecord->id,
409                             'assignment' => $configrecord->assignment,
410                             'plugin' => $configrecord->plugin,
411                             'subtype' => $configrecord->subtype,
412                             'name' => $configrecord->name,
413                             'value' => $configrecord->value
414                         );
415                     }
416                     $configrecords->close();
418                     $assignment = array(
419                         'id' => $module->assignmentid,
420                         'cmid' => $module->id,
421                         'course' => $module->course,
422                         'name' => $module->name,
423                         'nosubmissions' => $module->nosubmissions,
424                         'submissiondrafts' => $module->submissiondrafts,
425                         'sendnotifications' => $module->sendnotifications,
426                         'sendlatenotifications' => $module->sendlatenotifications,
427                         'sendstudentnotifications' => $module->sendstudentnotifications,
428                         'duedate' => $module->duedate,
429                         'allowsubmissionsfromdate' => $module->allowsubmissionsfromdate,
430                         'grade' => $module->grade,
431                         'timemodified' => $module->timemodified,
432                         'completionsubmit' => $module->completionsubmit,
433                         'cutoffdate' => $module->cutoffdate,
434                         'teamsubmission' => $module->teamsubmission,
435                         'requireallteammemberssubmit' => $module->requireallteammemberssubmit,
436                         'teamsubmissiongroupingid' => $module->teamsubmissiongroupingid,
437                         'blindmarking' => $module->blindmarking,
438                         'revealidentities' => $module->revealidentities,
439                         'attemptreopenmethod' => $module->attemptreopenmethod,
440                         'maxattempts' => $module->maxattempts,
441                         'markingworkflow' => $module->markingworkflow,
442                         'markingallocation' => $module->markingallocation,
443                         'requiresubmissionstatement' => $module->requiresubmissionstatement,
444                         'preventsubmissionnotingroup' => $module->preventsubmissionnotingroup,
445                         'configs' => $configarray
446                     );
448                     // Return or not intro and file attachments depending on the plugin settings.
449                     $assign = new assign($context, null, null);
451                     if ($assign->show_intro()) {
453                         list($assignment['intro'], $assignment['introformat']) = external_format_text($module->intro,
454                             $module->introformat, $context->id, 'mod_assign', 'intro', null);
455                         $assignment['introfiles'] = external_util::get_area_files($context->id, 'mod_assign', 'intro', false,
456                                                                                     false);
458                         $fs = get_file_storage();
459                         if ($files = $fs->get_area_files($context->id, 'mod_assign', ASSIGN_INTROATTACHMENT_FILEAREA,
460                                                             0, 'timemodified', false)) {
462                             $assignment['introattachments'] = array();
463                             foreach ($files as $file) {
464                                 $filename = $file->get_filename();
466                                 $assignment['introattachments'][] = array(
467                                     'filename' => $filename,
468                                     'mimetype' => $file->get_mimetype(),
469                                     'fileurl'  => moodle_url::make_webservice_pluginfile_url(
470                                         $context->id, 'mod_assign', ASSIGN_INTROATTACHMENT_FILEAREA, 0, '/', $filename)->out(false)
471                                 );
472                             }
473                         }
474                     }
476                     $assignmentarray[] = $assignment;
477                 }
478             }
479             $coursearray[]= array(
480                 'id' => $courses[$id]->id,
481                 'fullname' => external_format_string($courses[$id]->fullname, $course->contextid),
482                 'shortname' => external_format_string($courses[$id]->shortname, $course->contextid),
483                 'timemodified' => $courses[$id]->timemodified,
484                 'assignments' => $assignmentarray
485             );
486         }
488         $result = array(
489             'courses' => $coursearray,
490             'warnings' => $warnings
491         );
492         return $result;
493     }
495     /**
496      * Creates an assignment external_single_structure
497      *
498      * @return external_single_structure
499      * @since Moodle 2.4
500      */
501     private static function get_assignments_assignment_structure() {
502         return new external_single_structure(
503             array(
504                 'id' => new external_value(PARAM_INT, 'assignment id'),
505                 'cmid' => new external_value(PARAM_INT, 'course module id'),
506                 'course' => new external_value(PARAM_INT, 'course id'),
507                 'name' => new external_value(PARAM_TEXT, 'assignment name'),
508                 'nosubmissions' => new external_value(PARAM_INT, 'no submissions'),
509                 'submissiondrafts' => new external_value(PARAM_INT, 'submissions drafts'),
510                 'sendnotifications' => new external_value(PARAM_INT, 'send notifications'),
511                 'sendlatenotifications' => new external_value(PARAM_INT, 'send notifications'),
512                 'sendstudentnotifications' => new external_value(PARAM_INT, 'send student notifications (default)'),
513                 'duedate' => new external_value(PARAM_INT, 'assignment due date'),
514                 'allowsubmissionsfromdate' => new external_value(PARAM_INT, 'allow submissions from date'),
515                 'grade' => new external_value(PARAM_INT, 'grade type'),
516                 'timemodified' => new external_value(PARAM_INT, 'last time assignment was modified'),
517                 'completionsubmit' => new external_value(PARAM_INT, 'if enabled, set activity as complete following submission'),
518                 'cutoffdate' => new external_value(PARAM_INT, 'date after which submission is not accepted without an extension'),
519                 'teamsubmission' => new external_value(PARAM_INT, 'if enabled, students submit as a team'),
520                 'requireallteammemberssubmit' => new external_value(PARAM_INT, 'if enabled, all team members must submit'),
521                 'teamsubmissiongroupingid' => new external_value(PARAM_INT, 'the grouping id for the team submission groups'),
522                 'blindmarking' => new external_value(PARAM_INT, 'if enabled, hide identities until reveal identities actioned'),
523                 'revealidentities' => new external_value(PARAM_INT, 'show identities for a blind marking assignment'),
524                 'attemptreopenmethod' => new external_value(PARAM_TEXT, 'method used to control opening new attempts'),
525                 'maxattempts' => new external_value(PARAM_INT, 'maximum number of attempts allowed'),
526                 'markingworkflow' => new external_value(PARAM_INT, 'enable marking workflow'),
527                 'markingallocation' => new external_value(PARAM_INT, 'enable marking allocation'),
528                 'requiresubmissionstatement' => new external_value(PARAM_INT, 'student must accept submission statement'),
529                 'preventsubmissionnotingroup' => new external_value(PARAM_INT, 'Prevent submission not in group', VALUE_OPTIONAL),
530                 'configs' => new external_multiple_structure(self::get_assignments_config_structure(), 'configuration settings'),
531                 'intro' => new external_value(PARAM_RAW,
532                     'assignment intro, not allways returned because it deppends on the activity configuration', VALUE_OPTIONAL),
533                 'introformat' => new external_format_value('intro', VALUE_OPTIONAL),
534                 'introfiles' => new external_files('Files in the introduction text', VALUE_OPTIONAL),
535                 'introattachments' => new external_multiple_structure(
536                     new external_single_structure(
537                         array (
538                             'filename' => new external_value(PARAM_FILE, 'file name'),
539                             'mimetype' => new external_value(PARAM_RAW, 'mime type'),
540                             'fileurl'  => new external_value(PARAM_URL, 'file download url')
541                         )
542                     ), 'intro attachments files', VALUE_OPTIONAL
543                 )
544             ), 'assignment information object');
545     }
547     /**
548      * Creates an assign_plugin_config external_single_structure
549      *
550      * @return external_single_structure
551      * @since Moodle 2.4
552      */
553     private static function get_assignments_config_structure() {
554         return new external_single_structure(
555             array(
556                 'id' => new external_value(PARAM_INT, 'assign_plugin_config id'),
557                 'assignment' => new external_value(PARAM_INT, 'assignment id'),
558                 'plugin' => new external_value(PARAM_TEXT, 'plugin'),
559                 'subtype' => new external_value(PARAM_TEXT, 'subtype'),
560                 'name' => new external_value(PARAM_TEXT, 'name'),
561                 'value' => new external_value(PARAM_TEXT, 'value')
562             ), 'assignment configuration object'
563         );
564     }
566     /**
567      * Creates a course external_single_structure
568      *
569      * @return external_single_structure
570      * @since Moodle 2.4
571      */
572     private static function get_assignments_course_structure() {
573         return new external_single_structure(
574             array(
575                 'id' => new external_value(PARAM_INT, 'course id'),
576                 'fullname' => new external_value(PARAM_TEXT, 'course full name'),
577                 'shortname' => new external_value(PARAM_TEXT, 'course short name'),
578                 'timemodified' => new external_value(PARAM_INT, 'last time modified'),
579                 'assignments' => new external_multiple_structure(self::get_assignments_assignment_structure(), 'assignment info')
580               ), 'course information object'
581         );
582     }
584     /**
585      * Describes the return value for get_assignments
586      *
587      * @return external_single_structure
588      * @since Moodle 2.4
589      */
590     public static function get_assignments_returns() {
591         return new external_single_structure(
592             array(
593                 'courses' => new external_multiple_structure(self::get_assignments_course_structure(), 'list of courses'),
594                 'warnings'  => new external_warnings('item can be \'course\' (errorcode 1 or 2) or \'module\' (errorcode 1)',
595                     'When item is a course then itemid is a course id. When the item is a module then itemid is a module id',
596                     'errorcode can be 1 (no access rights) or 2 (not enrolled or no permissions)')
597             )
598         );
599     }
601     /**
602      * Return information (files and text fields) for the given plugins in the assignment.
603      *
604      * @param  assign $assign the assignment object
605      * @param  array $assignplugins array of assignment plugins (submission or feedback)
606      * @param  stdClass $item the item object (submission or grade)
607      * @return array an array containing the plugins returned information
608      */
609     private static function get_plugins_data($assign, $assignplugins, $item) {
610         global $CFG;
612         $plugins = array();
613         $fs = get_file_storage();
615         foreach ($assignplugins as $assignplugin) {
617             if (!$assignplugin->is_enabled() or !$assignplugin->is_visible()) {
618                 continue;
619             }
621             $plugin = array(
622                 'name' => $assignplugin->get_name(),
623                 'type' => $assignplugin->get_type()
624             );
625             // Subtype is 'assignsubmission', type is currently 'file' or 'onlinetext'.
626             $component = $assignplugin->get_subtype().'_'.$assignplugin->get_type();
628             $fileareas = $assignplugin->get_file_areas();
629             foreach ($fileareas as $filearea => $name) {
630                 $fileareainfo = array('area' => $filearea);
631                 $files = $fs->get_area_files(
632                     $assign->get_context()->id,
633                     $component,
634                     $filearea,
635                     $item->id,
636                     "timemodified",
637                     false
638                 );
639                 foreach ($files as $file) {
640                     $filepath = $file->get_filepath().$file->get_filename();
641                     $fileurl = file_encode_url($CFG->wwwroot . '/webservice/pluginfile.php', '/' . $assign->get_context()->id .
642                         '/' . $component. '/'. $filearea . '/' . $item->id . $filepath);
643                     $fileinfo = array(
644                         'filepath' => $filepath,
645                         'fileurl' => $fileurl
646                         );
647                     $fileareainfo['files'][] = $fileinfo;
648                 }
649                 $plugin['fileareas'][] = $fileareainfo;
650             }
652             $editorfields = $assignplugin->get_editor_fields();
653             foreach ($editorfields as $name => $description) {
654                 $editorfieldinfo = array(
655                     'name' => $name,
656                     'description' => $description,
657                     'text' => $assignplugin->get_editor_text($name, $item->id),
658                     'format' => $assignplugin->get_editor_format($name, $item->id)
659                 );
660                 $plugin['editorfields'][] = $editorfieldinfo;
661             }
662             $plugins[] = $plugin;
663         }
664         return $plugins;
665     }
667     /**
668      * Describes the parameters for get_submissions
669      *
670      * @return external_external_function_parameters
671      * @since Moodle 2.5
672      */
673     public static function get_submissions_parameters() {
674         return new external_function_parameters(
675             array(
676                 'assignmentids' => new external_multiple_structure(
677                     new external_value(PARAM_INT, 'assignment id'),
678                     '1 or more assignment ids',
679                     VALUE_REQUIRED),
680                 'status' => new external_value(PARAM_ALPHA, 'status', VALUE_DEFAULT, ''),
681                 'since' => new external_value(PARAM_INT, 'submitted since', VALUE_DEFAULT, 0),
682                 'before' => new external_value(PARAM_INT, 'submitted before', VALUE_DEFAULT, 0)
683             )
684         );
685     }
687     /**
688      * Returns submissions for the requested assignment ids
689      *
690      * @param int[] $assignmentids
691      * @param string $status only return submissions with this status
692      * @param int $since only return submissions with timemodified >= since
693      * @param int $before only return submissions with timemodified <= before
694      * @return array of submissions for each requested assignment
695      * @since Moodle 2.5
696      */
697     public static function get_submissions($assignmentids, $status = '', $since = 0, $before = 0) {
698         global $DB, $CFG;
700         $params = self::validate_parameters(self::get_submissions_parameters(),
701                         array('assignmentids' => $assignmentids,
702                               'status' => $status,
703                               'since' => $since,
704                               'before' => $before));
706         $warnings = array();
707         $assignments = array();
709         // Check the user is allowed to get the submissions for the assignments requested.
710         $placeholders = array();
711         list($inorequalsql, $placeholders) = $DB->get_in_or_equal($params['assignmentids'], SQL_PARAMS_NAMED);
712         $sql = "SELECT cm.id, cm.instance FROM {course_modules} cm JOIN {modules} md ON md.id = cm.module ".
713                "WHERE md.name = :modname AND cm.instance ".$inorequalsql;
714         $placeholders['modname'] = 'assign';
715         $cms = $DB->get_records_sql($sql, $placeholders);
716         $assigns = array();
717         foreach ($cms as $cm) {
718             try {
719                 $context = context_module::instance($cm->id);
720                 self::validate_context($context);
721                 require_capability('mod/assign:grade', $context);
722                 $assign = new assign($context, null, null);
723                 $assigns[] = $assign;
724             } catch (Exception $e) {
725                 $warnings[] = array(
726                     'item' => 'assignment',
727                     'itemid' => $cm->instance,
728                     'warningcode' => '1',
729                     'message' => 'No access rights in module context'
730                 );
731             }
732         }
734         foreach ($assigns as $assign) {
735             $submissions = array();
736             $placeholders = array('assignid1' => $assign->get_instance()->id,
737                                   'assignid2' => $assign->get_instance()->id);
739             $submissionmaxattempt = 'SELECT mxs.userid, MAX(mxs.attemptnumber) AS maxattempt
740                                      FROM {assign_submission} mxs
741                                      WHERE mxs.assignment = :assignid1 GROUP BY mxs.userid';
743             $sql = "SELECT mas.id, mas.assignment,mas.userid,".
744                    "mas.timecreated,mas.timemodified,mas.status,mas.groupid,mas.attemptnumber ".
745                    "FROM {assign_submission} mas ".
746                    "JOIN ( " . $submissionmaxattempt . " ) smx ON mas.userid = smx.userid ".
747                    "WHERE mas.assignment = :assignid2 AND mas.attemptnumber = smx.maxattempt";
749             if (!empty($params['status'])) {
750                 $placeholders['status'] = $params['status'];
751                 $sql = $sql." AND mas.status = :status";
752             }
753             if (!empty($params['before'])) {
754                 $placeholders['since'] = $params['since'];
755                 $placeholders['before'] = $params['before'];
756                 $sql = $sql." AND mas.timemodified BETWEEN :since AND :before";
757             } else {
758                 $placeholders['since'] = $params['since'];
759                 $sql = $sql." AND mas.timemodified >= :since";
760             }
762             $submissionrecords = $DB->get_records_sql($sql, $placeholders);
764             if (!empty($submissionrecords)) {
765                 $submissionplugins = $assign->get_submission_plugins();
766                 foreach ($submissionrecords as $submissionrecord) {
767                     $submission = array(
768                         'id' => $submissionrecord->id,
769                         'userid' => $submissionrecord->userid,
770                         'timecreated' => $submissionrecord->timecreated,
771                         'timemodified' => $submissionrecord->timemodified,
772                         'status' => $submissionrecord->status,
773                         'attemptnumber' => $submissionrecord->attemptnumber,
774                         'groupid' => $submissionrecord->groupid,
775                         'plugins' => self::get_plugins_data($assign, $submissionplugins, $submissionrecord)
776                     );
777                     $submissions[] = $submission;
778                 }
779             } else {
780                 $warnings[] = array(
781                     'item' => 'module',
782                     'itemid' => $assign->get_instance()->id,
783                     'warningcode' => '3',
784                     'message' => 'No submissions found'
785                 );
786             }
788             $assignments[] = array(
789                 'assignmentid' => $assign->get_instance()->id,
790                 'submissions' => $submissions
791             );
793         }
795         $result = array(
796             'assignments' => $assignments,
797             'warnings' => $warnings
798         );
799         return $result;
800     }
802     /**
803      * Creates an assignment plugin structure.
804      *
805      * @return external_single_structure the plugin structure
806      */
807     private static function get_plugin_structure() {
808         return new external_single_structure(
809             array(
810                 'type' => new external_value(PARAM_TEXT, 'submission plugin type'),
811                 'name' => new external_value(PARAM_TEXT, 'submission plugin name'),
812                 'fileareas' => new external_multiple_structure(
813                     new external_single_structure(
814                         array (
815                             'area' => new external_value (PARAM_TEXT, 'file area'),
816                             'files' => new external_multiple_structure(
817                                 new external_single_structure(
818                                     array (
819                                         'filepath' => new external_value (PARAM_TEXT, 'file path'),
820                                         'fileurl' => new external_value (PARAM_URL, 'file download url',
821                                             VALUE_OPTIONAL)
822                                     )
823                                 ), 'files', VALUE_OPTIONAL
824                             )
825                         )
826                     ), 'fileareas', VALUE_OPTIONAL
827                 ),
828                 'editorfields' => new external_multiple_structure(
829                     new external_single_structure(
830                         array(
831                             'name' => new external_value(PARAM_TEXT, 'field name'),
832                             'description' => new external_value(PARAM_TEXT, 'field description'),
833                             'text' => new external_value (PARAM_RAW, 'field value'),
834                             'format' => new external_format_value ('text')
835                         )
836                     )
837                     , 'editorfields', VALUE_OPTIONAL
838                 )
839             )
840         );
841     }
843     /**
844      * Creates a submission structure.
845      *
846      * @return external_single_structure the submission structure
847      */
848     private static function get_submission_structure($required = VALUE_REQUIRED) {
849         return new external_single_structure(
850             array(
851                 'id' => new external_value(PARAM_INT, 'submission id'),
852                 'userid' => new external_value(PARAM_INT, 'student id'),
853                 'attemptnumber' => new external_value(PARAM_INT, 'attempt number'),
854                 'timecreated' => new external_value(PARAM_INT, 'submission creation time'),
855                 'timemodified' => new external_value(PARAM_INT, 'submission last modified time'),
856                 'status' => new external_value(PARAM_TEXT, 'submission status'),
857                 'groupid' => new external_value(PARAM_INT, 'group id'),
858                 'assignment' => new external_value(PARAM_INT, 'assignment id', VALUE_OPTIONAL),
859                 'latest' => new external_value(PARAM_INT, 'latest attempt', VALUE_OPTIONAL),
860                 'plugins' => new external_multiple_structure(self::get_plugin_structure(), 'plugins', VALUE_OPTIONAL)
861             ), 'submission info', $required
862         );
863     }
865     /**
866      * Creates an assign_submissions external_single_structure
867      *
868      * @return external_single_structure
869      * @since Moodle 2.5
870      */
871     private static function get_submissions_structure() {
872         return new external_single_structure(
873             array (
874                 'assignmentid' => new external_value(PARAM_INT, 'assignment id'),
875                 'submissions' => new external_multiple_structure(self::get_submission_structure())
876             )
877         );
878     }
880     /**
881      * Describes the get_submissions return value
882      *
883      * @return external_single_structure
884      * @since Moodle 2.5
885      */
886     public static function get_submissions_returns() {
887         return new external_single_structure(
888             array(
889                 'assignments' => new external_multiple_structure(self::get_submissions_structure(), 'assignment submissions'),
890                 'warnings' => new external_warnings()
891             )
892         );
893     }
895     /**
896      * Describes the parameters for set_user_flags
897      * @return external_function_parameters
898      * @since  Moodle 2.6
899      */
900     public static function set_user_flags_parameters() {
901         return new external_function_parameters(
902             array(
903                 'assignmentid'    => new external_value(PARAM_INT, 'assignment id'),
904                 'userflags' => new external_multiple_structure(
905                     new external_single_structure(
906                         array(
907                             'userid'           => new external_value(PARAM_INT, 'student id'),
908                             'locked'           => new external_value(PARAM_INT, 'locked', VALUE_OPTIONAL),
909                             'mailed'           => new external_value(PARAM_INT, 'mailed', VALUE_OPTIONAL),
910                             'extensionduedate' => new external_value(PARAM_INT, 'extension due date', VALUE_OPTIONAL),
911                             'workflowstate'    => new external_value(PARAM_TEXT, 'marking workflow state', VALUE_OPTIONAL),
912                             'allocatedmarker'  => new external_value(PARAM_INT, 'allocated marker', VALUE_OPTIONAL)
913                         )
914                     )
915                 )
916             )
917         );
918     }
920     /**
921      * Create or update user_flags records
922      *
923      * @param int $assignmentid the assignment for which the userflags are created or updated
924      * @param array $userflags  An array of userflags to create or update
925      * @return array containing success or failure information for each record
926      * @since Moodle 2.6
927      */
928     public static function set_user_flags($assignmentid, $userflags = array()) {
929         global $CFG, $DB;
931         $params = self::validate_parameters(self::set_user_flags_parameters(),
932                                             array('assignmentid' => $assignmentid,
933                                                   'userflags' => $userflags));
935         // Load assignment if it exists and if the user has the capability.
936         list($assign, $course, $cm, $context) = self::validate_assign($params['assignmentid']);
937         require_capability('mod/assign:grade', $context);
939         $results = array();
940         foreach ($params['userflags'] as $userflag) {
941             $success = true;
942             $result = array();
944             $record = $assign->get_user_flags($userflag['userid'], false);
945             if ($record) {
946                 if (isset($userflag['locked'])) {
947                     $record->locked = $userflag['locked'];
948                 }
949                 if (isset($userflag['mailed'])) {
950                     $record->mailed = $userflag['mailed'];
951                 }
952                 if (isset($userflag['extensionduedate'])) {
953                     $record->extensionduedate = $userflag['extensionduedate'];
954                 }
955                 if (isset($userflag['workflowstate'])) {
956                     $record->workflowstate = $userflag['workflowstate'];
957                 }
958                 if (isset($userflag['allocatedmarker'])) {
959                     $record->allocatedmarker = $userflag['allocatedmarker'];
960                 }
961                 if ($assign->update_user_flags($record)) {
962                     $result['id'] = $record->id;
963                     $result['userid'] = $userflag['userid'];
964                 } else {
965                     $result['id'] = $record->id;
966                     $result['userid'] = $userflag['userid'];
967                     $result['errormessage'] = 'Record created but values could not be set';
968                 }
969             } else {
970                 $record = $assign->get_user_flags($userflag['userid'], true);
971                 $setfields = isset($userflag['locked'])
972                              || isset($userflag['mailed'])
973                              || isset($userflag['extensionduedate'])
974                              || isset($userflag['workflowstate'])
975                              || isset($userflag['allocatedmarker']);
976                 if ($record) {
977                     if ($setfields) {
978                         if (isset($userflag['locked'])) {
979                             $record->locked = $userflag['locked'];
980                         }
981                         if (isset($userflag['mailed'])) {
982                             $record->mailed = $userflag['mailed'];
983                         }
984                         if (isset($userflag['extensionduedate'])) {
985                             $record->extensionduedate = $userflag['extensionduedate'];
986                         }
987                         if (isset($userflag['workflowstate'])) {
988                             $record->workflowstate = $userflag['workflowstate'];
989                         }
990                         if (isset($userflag['allocatedmarker'])) {
991                             $record->allocatedmarker = $userflag['allocatedmarker'];
992                         }
993                         if ($assign->update_user_flags($record)) {
994                             $result['id'] = $record->id;
995                             $result['userid'] = $userflag['userid'];
996                         } else {
997                             $result['id'] = $record->id;
998                             $result['userid'] = $userflag['userid'];
999                             $result['errormessage'] = 'Record created but values could not be set';
1000                         }
1001                     } else {
1002                         $result['id'] = $record->id;
1003                         $result['userid'] = $userflag['userid'];
1004                     }
1005                 } else {
1006                     $result['id'] = -1;
1007                     $result['userid'] = $userflag['userid'];
1008                     $result['errormessage'] = 'Record could not be created';
1009                 }
1010             }
1012             $results[] = $result;
1013         }
1014         return $results;
1015     }
1017     /**
1018      * Describes the set_user_flags return value
1019      * @return external_multiple_structure
1020      * @since  Moodle 2.6
1021      */
1022     public static function set_user_flags_returns() {
1023         return new external_multiple_structure(
1024             new external_single_structure(
1025                 array(
1026                     'id' => new external_value(PARAM_INT, 'id of record if successful, -1 for failure'),
1027                     'userid' => new external_value(PARAM_INT, 'userid of record'),
1028                     'errormessage' => new external_value(PARAM_TEXT, 'Failure error message', VALUE_OPTIONAL)
1029                 )
1030             )
1031         );
1032     }
1034     /**
1035      * Describes the parameters for get_user_flags
1036      * @return external_function_parameters
1037      * @since  Moodle 2.6
1038      */
1039     public static function get_user_flags_parameters() {
1040         return new external_function_parameters(
1041             array(
1042                 'assignmentids' => new external_multiple_structure(
1043                     new external_value(PARAM_INT, 'assignment id'),
1044                     '1 or more assignment ids',
1045                     VALUE_REQUIRED)
1046             )
1047         );
1048     }
1050     /**
1051      * Returns user flag information from assign_user_flags for the requested assignment ids
1052      * @param int[] $assignmentids
1053      * @return array of user flag records for each requested assignment
1054      * @since  Moodle 2.6
1055      */
1056     public static function get_user_flags($assignmentids) {
1057         global $DB;
1058         $params = self::validate_parameters(self::get_user_flags_parameters(),
1059                         array('assignmentids' => $assignmentids));
1061         $assignments = array();
1062         $warnings = array();
1063         $requestedassignmentids = $params['assignmentids'];
1065         // Check the user is allowed to get the user flags for the assignments requested.
1066         $placeholders = array();
1067         list($sqlassignmentids, $placeholders) = $DB->get_in_or_equal($requestedassignmentids, SQL_PARAMS_NAMED);
1068         $sql = "SELECT cm.id, cm.instance FROM {course_modules} cm JOIN {modules} md ON md.id = cm.module ".
1069                "WHERE md.name = :modname AND cm.instance ".$sqlassignmentids;
1070         $placeholders['modname'] = 'assign';
1071         $cms = $DB->get_records_sql($sql, $placeholders);
1072         foreach ($cms as $cm) {
1073             try {
1074                 $context = context_module::instance($cm->id);
1075                 self::validate_context($context);
1076                 require_capability('mod/assign:grade', $context);
1077             } catch (Exception $e) {
1078                 $requestedassignmentids = array_diff($requestedassignmentids, array($cm->instance));
1079                 $warning = array();
1080                 $warning['item'] = 'assignment';
1081                 $warning['itemid'] = $cm->instance;
1082                 $warning['warningcode'] = '1';
1083                 $warning['message'] = 'No access rights in module context';
1084                 $warnings[] = $warning;
1085             }
1086         }
1088         // Create the query and populate an array of assign_user_flags records from the recordset results.
1089         if (count ($requestedassignmentids) > 0) {
1090             $placeholders = array();
1091             list($inorequalsql, $placeholders) = $DB->get_in_or_equal($requestedassignmentids, SQL_PARAMS_NAMED);
1093             $sql = "SELECT auf.id,auf.assignment,auf.userid,auf.locked,auf.mailed,".
1094                    "auf.extensionduedate,auf.workflowstate,auf.allocatedmarker ".
1095                    "FROM {assign_user_flags} auf ".
1096                    "WHERE auf.assignment ".$inorequalsql.
1097                    " ORDER BY auf.assignment, auf.id";
1099             $rs = $DB->get_recordset_sql($sql, $placeholders);
1100             $currentassignmentid = null;
1101             $assignment = null;
1102             foreach ($rs as $rd) {
1103                 $userflag = array();
1104                 $userflag['id'] = $rd->id;
1105                 $userflag['userid'] = $rd->userid;
1106                 $userflag['locked'] = $rd->locked;
1107                 $userflag['mailed'] = $rd->mailed;
1108                 $userflag['extensionduedate'] = $rd->extensionduedate;
1109                 $userflag['workflowstate'] = $rd->workflowstate;
1110                 $userflag['allocatedmarker'] = $rd->allocatedmarker;
1112                 if (is_null($currentassignmentid) || ($rd->assignment != $currentassignmentid )) {
1113                     if (!is_null($assignment)) {
1114                         $assignments[] = $assignment;
1115                     }
1116                     $assignment = array();
1117                     $assignment['assignmentid'] = $rd->assignment;
1118                     $assignment['userflags'] = array();
1119                     $requestedassignmentids = array_diff($requestedassignmentids, array($rd->assignment));
1120                 }
1121                 $assignment['userflags'][] = $userflag;
1123                 $currentassignmentid = $rd->assignment;
1124             }
1125             if (!is_null($assignment)) {
1126                 $assignments[] = $assignment;
1127             }
1128             $rs->close();
1130         }
1132         foreach ($requestedassignmentids as $assignmentid) {
1133             $warning = array();
1134             $warning['item'] = 'assignment';
1135             $warning['itemid'] = $assignmentid;
1136             $warning['warningcode'] = '3';
1137             $warning['message'] = 'No user flags found';
1138             $warnings[] = $warning;
1139         }
1141         $result = array();
1142         $result['assignments'] = $assignments;
1143         $result['warnings'] = $warnings;
1144         return $result;
1145     }
1147     /**
1148      * Creates an assign_user_flags external_single_structure
1149      * @return external_single_structure
1150      * @since  Moodle 2.6
1151      */
1152     private static function assign_user_flags() {
1153         return new external_single_structure(
1154             array (
1155                 'assignmentid'    => new external_value(PARAM_INT, 'assignment id'),
1156                 'userflags'   => new external_multiple_structure(new external_single_structure(
1157                         array(
1158                             'id'               => new external_value(PARAM_INT, 'user flag id'),
1159                             'userid'           => new external_value(PARAM_INT, 'student id'),
1160                             'locked'           => new external_value(PARAM_INT, 'locked'),
1161                             'mailed'           => new external_value(PARAM_INT, 'mailed'),
1162                             'extensionduedate' => new external_value(PARAM_INT, 'extension due date'),
1163                             'workflowstate'    => new external_value(PARAM_TEXT, 'marking workflow state', VALUE_OPTIONAL),
1164                             'allocatedmarker'  => new external_value(PARAM_INT, 'allocated marker')
1165                         )
1166                     )
1167                 )
1168             )
1169         );
1170     }
1172     /**
1173      * Describes the get_user_flags return value
1174      * @return external_single_structure
1175      * @since  Moodle 2.6
1176      */
1177     public static function get_user_flags_returns() {
1178         return new external_single_structure(
1179             array(
1180                 'assignments' => new external_multiple_structure(self::assign_user_flags(), 'list of assign user flag information'),
1181                 'warnings'      => new external_warnings('item is always \'assignment\'',
1182                     'when errorcode is 3 then itemid is an assignment id. When errorcode is 1, itemid is a course module id',
1183                     'errorcode can be 3 (no user flags found) or 1 (no permission to get user flags)')
1184             )
1185         );
1186     }
1188     /**
1189      * Describes the parameters for get_user_mappings
1190      * @return external_function_parameters
1191      * @since  Moodle 2.6
1192      */
1193     public static function get_user_mappings_parameters() {
1194         return new external_function_parameters(
1195             array(
1196                 'assignmentids' => new external_multiple_structure(
1197                     new external_value(PARAM_INT, 'assignment id'),
1198                     '1 or more assignment ids',
1199                     VALUE_REQUIRED)
1200             )
1201         );
1202     }
1204     /**
1205      * Returns user mapping information from assign_user_mapping for the requested assignment ids
1206      * @param int[] $assignmentids
1207      * @return array of user mapping records for each requested assignment
1208      * @since  Moodle 2.6
1209      */
1210     public static function get_user_mappings($assignmentids) {
1211         global $DB;
1212         $params = self::validate_parameters(self::get_user_mappings_parameters(),
1213                         array('assignmentids' => $assignmentids));
1215         $assignments = array();
1216         $warnings = array();
1217         $requestedassignmentids = $params['assignmentids'];
1219         // Check the user is allowed to get the mappings for the assignments requested.
1220         $placeholders = array();
1221         list($sqlassignmentids, $placeholders) = $DB->get_in_or_equal($requestedassignmentids, SQL_PARAMS_NAMED);
1222         $sql = "SELECT cm.id, cm.instance FROM {course_modules} cm JOIN {modules} md ON md.id = cm.module ".
1223                "WHERE md.name = :modname AND cm.instance ".$sqlassignmentids;
1224         $placeholders['modname'] = 'assign';
1225         $cms = $DB->get_records_sql($sql, $placeholders);
1226         foreach ($cms as $cm) {
1227             try {
1228                 $context = context_module::instance($cm->id);
1229                 self::validate_context($context);
1230                 require_capability('mod/assign:revealidentities', $context);
1231             } catch (Exception $e) {
1232                 $requestedassignmentids = array_diff($requestedassignmentids, array($cm->instance));
1233                 $warning = array();
1234                 $warning['item'] = 'assignment';
1235                 $warning['itemid'] = $cm->instance;
1236                 $warning['warningcode'] = '1';
1237                 $warning['message'] = 'No access rights in module context';
1238                 $warnings[] = $warning;
1239             }
1240         }
1242         // Create the query and populate an array of assign_user_mapping records from the recordset results.
1243         if (count ($requestedassignmentids) > 0) {
1244             $placeholders = array();
1245             list($inorequalsql, $placeholders) = $DB->get_in_or_equal($requestedassignmentids, SQL_PARAMS_NAMED);
1247             $sql = "SELECT aum.id,aum.assignment,aum.userid ".
1248                    "FROM {assign_user_mapping} aum ".
1249                    "WHERE aum.assignment ".$inorequalsql.
1250                    " ORDER BY aum.assignment, aum.id";
1252             $rs = $DB->get_recordset_sql($sql, $placeholders);
1253             $currentassignmentid = null;
1254             $assignment = null;
1255             foreach ($rs as $rd) {
1256                 $mapping = array();
1257                 $mapping['id'] = $rd->id;
1258                 $mapping['userid'] = $rd->userid;
1260                 if (is_null($currentassignmentid) || ($rd->assignment != $currentassignmentid )) {
1261                     if (!is_null($assignment)) {
1262                         $assignments[] = $assignment;
1263                     }
1264                     $assignment = array();
1265                     $assignment['assignmentid'] = $rd->assignment;
1266                     $assignment['mappings'] = array();
1267                     $requestedassignmentids = array_diff($requestedassignmentids, array($rd->assignment));
1268                 }
1269                 $assignment['mappings'][] = $mapping;
1271                 $currentassignmentid = $rd->assignment;
1272             }
1273             if (!is_null($assignment)) {
1274                 $assignments[] = $assignment;
1275             }
1276             $rs->close();
1278         }
1280         foreach ($requestedassignmentids as $assignmentid) {
1281             $warning = array();
1282             $warning['item'] = 'assignment';
1283             $warning['itemid'] = $assignmentid;
1284             $warning['warningcode'] = '3';
1285             $warning['message'] = 'No mappings found';
1286             $warnings[] = $warning;
1287         }
1289         $result = array();
1290         $result['assignments'] = $assignments;
1291         $result['warnings'] = $warnings;
1292         return $result;
1293     }
1295     /**
1296      * Creates an assign_user_mappings external_single_structure
1297      * @return external_single_structure
1298      * @since  Moodle 2.6
1299      */
1300     private static function assign_user_mappings() {
1301         return new external_single_structure(
1302             array (
1303                 'assignmentid'    => new external_value(PARAM_INT, 'assignment id'),
1304                 'mappings'   => new external_multiple_structure(new external_single_structure(
1305                         array(
1306                             'id'     => new external_value(PARAM_INT, 'user mapping id'),
1307                             'userid' => new external_value(PARAM_INT, 'student id')
1308                         )
1309                     )
1310                 )
1311             )
1312         );
1313     }
1315     /**
1316      * Describes the get_user_mappings return value
1317      * @return external_single_structure
1318      * @since  Moodle 2.6
1319      */
1320     public static function get_user_mappings_returns() {
1321         return new external_single_structure(
1322             array(
1323                 'assignments' => new external_multiple_structure(self::assign_user_mappings(), 'list of assign user mapping data'),
1324                 'warnings'      => new external_warnings('item is always \'assignment\'',
1325                     'when errorcode is 3 then itemid is an assignment id. When errorcode is 1, itemid is a course module id',
1326                     'errorcode can be 3 (no user mappings found) or 1 (no permission to get user mappings)')
1327             )
1328         );
1329     }
1331     /**
1332      * Describes the parameters for lock_submissions
1333      * @return external_external_function_parameters
1334      * @since  Moodle 2.6
1335      */
1336     public static function lock_submissions_parameters() {
1337         return new external_function_parameters(
1338             array(
1339                 'assignmentid' => new external_value(PARAM_INT, 'The assignment id to operate on'),
1340                 'userids' => new external_multiple_structure(
1341                     new external_value(PARAM_INT, 'user id'),
1342                     '1 or more user ids',
1343                     VALUE_REQUIRED),
1344             )
1345         );
1346     }
1348     /**
1349      * Locks (prevent updates to) submissions in this assignment.
1350      *
1351      * @param int $assignmentid The id of the assignment
1352      * @param array $userids Array of user ids to lock
1353      * @return array of warnings for each submission that could not be locked.
1354      * @since Moodle 2.6
1355      */
1356     public static function lock_submissions($assignmentid, $userids) {
1357         global $CFG;
1359         $params = self::validate_parameters(self::lock_submissions_parameters(),
1360                         array('assignmentid' => $assignmentid,
1361                               'userids' => $userids));
1363         list($assignment, $course, $cm, $context) = self::validate_assign($params['assignmentid']);
1365         $warnings = array();
1366         foreach ($params['userids'] as $userid) {
1367             if (!$assignment->lock_submission($userid)) {
1368                 $detail = 'User id: ' . $userid . ', Assignment id: ' . $params['assignmentid'];
1369                 $warnings[] = self::generate_warning($params['assignmentid'],
1370                                                      'couldnotlock',
1371                                                      $detail);
1372             }
1373         }
1375         return $warnings;
1376     }
1378     /**
1379      * Describes the return value for lock_submissions
1380      *
1381      * @return external_single_structure
1382      * @since Moodle 2.6
1383      */
1384     public static function lock_submissions_returns() {
1385         return new external_warnings();
1386     }
1388     /**
1389      * Describes the parameters for revert_submissions_to_draft
1390      * @return external_external_function_parameters
1391      * @since  Moodle 2.6
1392      */
1393     public static function revert_submissions_to_draft_parameters() {
1394         return new external_function_parameters(
1395             array(
1396                 'assignmentid' => new external_value(PARAM_INT, 'The assignment id to operate on'),
1397                 'userids' => new external_multiple_structure(
1398                     new external_value(PARAM_INT, 'user id'),
1399                     '1 or more user ids',
1400                     VALUE_REQUIRED),
1401             )
1402         );
1403     }
1405     /**
1406      * Reverts a list of user submissions to draft for a single assignment.
1407      *
1408      * @param int $assignmentid The id of the assignment
1409      * @param array $userids Array of user ids to revert
1410      * @return array of warnings for each submission that could not be reverted.
1411      * @since Moodle 2.6
1412      */
1413     public static function revert_submissions_to_draft($assignmentid, $userids) {
1414         global $CFG;
1416         $params = self::validate_parameters(self::revert_submissions_to_draft_parameters(),
1417                         array('assignmentid' => $assignmentid,
1418                               'userids' => $userids));
1420         list($assignment, $course, $cm, $context) = self::validate_assign($params['assignmentid']);
1422         $warnings = array();
1423         foreach ($params['userids'] as $userid) {
1424             if (!$assignment->revert_to_draft($userid)) {
1425                 $detail = 'User id: ' . $userid . ', Assignment id: ' . $params['assignmentid'];
1426                 $warnings[] = self::generate_warning($params['assignmentid'],
1427                                                      'couldnotrevert',
1428                                                      $detail);
1429             }
1430         }
1432         return $warnings;
1433     }
1435     /**
1436      * Describes the return value for revert_submissions_to_draft
1437      *
1438      * @return external_single_structure
1439      * @since Moodle 2.6
1440      */
1441     public static function revert_submissions_to_draft_returns() {
1442         return new external_warnings();
1443     }
1445     /**
1446      * Describes the parameters for unlock_submissions
1447      * @return external_external_function_parameters
1448      * @since  Moodle 2.6
1449      */
1450     public static function unlock_submissions_parameters() {
1451         return new external_function_parameters(
1452             array(
1453                 'assignmentid' => new external_value(PARAM_INT, 'The assignment id to operate on'),
1454                 'userids' => new external_multiple_structure(
1455                     new external_value(PARAM_INT, 'user id'),
1456                     '1 or more user ids',
1457                     VALUE_REQUIRED),
1458             )
1459         );
1460     }
1462     /**
1463      * Locks (prevent updates to) submissions in this assignment.
1464      *
1465      * @param int $assignmentid The id of the assignment
1466      * @param array $userids Array of user ids to lock
1467      * @return array of warnings for each submission that could not be locked.
1468      * @since Moodle 2.6
1469      */
1470     public static function unlock_submissions($assignmentid, $userids) {
1471         global $CFG;
1473         $params = self::validate_parameters(self::unlock_submissions_parameters(),
1474                         array('assignmentid' => $assignmentid,
1475                               'userids' => $userids));
1477         list($assignment, $course, $cm, $context) = self::validate_assign($params['assignmentid']);
1479         $warnings = array();
1480         foreach ($params['userids'] as $userid) {
1481             if (!$assignment->unlock_submission($userid)) {
1482                 $detail = 'User id: ' . $userid . ', Assignment id: ' . $params['assignmentid'];
1483                 $warnings[] = self::generate_warning($params['assignmentid'],
1484                                                      'couldnotunlock',
1485                                                      $detail);
1486             }
1487         }
1489         return $warnings;
1490     }
1492     /**
1493      * Describes the return value for unlock_submissions
1494      *
1495      * @return external_single_structure
1496      * @since Moodle 2.6
1497      */
1498     public static function unlock_submissions_returns() {
1499         return new external_warnings();
1500     }
1502     /**
1503      * Describes the parameters for submit_grading_form webservice.
1504      * @return external_external_function_parameters
1505      * @since  Moodle 3.1
1506      */
1507     public static function submit_grading_form_parameters() {
1508         return new external_function_parameters(
1509             array(
1510                 'assignmentid' => new external_value(PARAM_INT, 'The assignment id to operate on'),
1511                 'userid' => new external_value(PARAM_INT, 'The user id the submission belongs to'),
1512                 'jsonformdata' => new external_value(PARAM_RAW, 'The data from the grading form, encoded as a json array')
1513             )
1514         );
1515     }
1517     /**
1518      * Submit the logged in users assignment for grading.
1519      *
1520      * @param int $assignmentid The id of the assignment
1521      * @param int $userid The id of the user the submission belongs to.
1522      * @param string $jsonformdata The data from the form, encoded as a json array.
1523      * @return array of warnings to indicate any errors.
1524      * @since Moodle 2.6
1525      */
1526     public static function submit_grading_form($assignmentid, $userid, $jsonformdata) {
1527         global $CFG, $USER;
1529         require_once($CFG->dirroot . '/mod/assign/locallib.php');
1530         require_once($CFG->dirroot . '/mod/assign/gradeform.php');
1532         $params = self::validate_parameters(self::submit_grading_form_parameters(),
1533                                             array(
1534                                                 'assignmentid' => $assignmentid,
1535                                                 'userid' => $userid,
1536                                                 'jsonformdata' => $jsonformdata
1537                                             ));
1539         list($assignment, $course, $cm, $context) = self::validate_assign($params['assignmentid']);
1541         $serialiseddata = json_decode($params['jsonformdata']);
1543         $data = array();
1544         parse_str($serialiseddata, $data);
1546         $warnings = array();
1548         $options = array(
1549             'userid' => $params['userid'],
1550             'attemptnumber' => $data['attemptnumber'],
1551             'rownum' => 0,
1552             'gradingpanel' => true
1553         );
1555         $customdata = (object) $data;
1556         $formparams = array($assignment, $customdata, $options);
1558         // Data is injected into the form by the last param for the constructor.
1559         $mform = new mod_assign_grade_form(null, $formparams, 'post', '', null, true, $data);
1560         $validateddata = $mform->get_data();
1562         if ($validateddata) {
1563             $assignment->save_grade($params['userid'], $validateddata);
1564         } else {
1565             $warnings[] = self::generate_warning($params['assignmentid'],
1566                                                  'couldnotsavegrade',
1567                                                  'Form validation failed.');
1568         }
1571         return $warnings;
1572     }
1574     /**
1575      * Describes the return for submit_grading_form
1576      * @return external_external_function_parameters
1577      * @since  Moodle 3.1
1578      */
1579     public static function submit_grading_form_returns() {
1580         return new external_warnings();
1581     }
1583     /**
1584      * Describes the parameters for submit_for_grading
1585      * @return external_external_function_parameters
1586      * @since  Moodle 2.6
1587      */
1588     public static function submit_for_grading_parameters() {
1589         return new external_function_parameters(
1590             array(
1591                 'assignmentid' => new external_value(PARAM_INT, 'The assignment id to operate on'),
1592                 'acceptsubmissionstatement' => new external_value(PARAM_BOOL, 'Accept the assignment submission statement')
1593             )
1594         );
1595     }
1597     /**
1598      * Submit the logged in users assignment for grading.
1599      *
1600      * @param int $assignmentid The id of the assignment
1601      * @return array of warnings to indicate any errors.
1602      * @since Moodle 2.6
1603      */
1604     public static function submit_for_grading($assignmentid, $acceptsubmissionstatement) {
1605         global $CFG, $USER;
1607         $params = self::validate_parameters(self::submit_for_grading_parameters(),
1608                                             array('assignmentid' => $assignmentid,
1609                                                   'acceptsubmissionstatement' => $acceptsubmissionstatement));
1611         list($assignment, $course, $cm, $context) = self::validate_assign($params['assignmentid']);
1613         $warnings = array();
1614         $data = new stdClass();
1615         $data->submissionstatement = $params['acceptsubmissionstatement'];
1616         $notices = array();
1618         if (!$assignment->submit_for_grading($data, $notices)) {
1619             $detail = 'User id: ' . $USER->id . ', Assignment id: ' . $params['assignmentid'] . ' Notices:' . implode(', ', $notices);
1620             $warnings[] = self::generate_warning($params['assignmentid'],
1621                                                  'couldnotsubmitforgrading',
1622                                                  $detail);
1623         }
1625         return $warnings;
1626     }
1628     /**
1629      * Describes the return value for submit_for_grading
1630      *
1631      * @return external_single_structure
1632      * @since Moodle 2.6
1633      */
1634     public static function submit_for_grading_returns() {
1635         return new external_warnings();
1636     }
1638     /**
1639      * Describes the parameters for save_user_extensions
1640      * @return external_external_function_parameters
1641      * @since  Moodle 2.6
1642      */
1643     public static function save_user_extensions_parameters() {
1644         return new external_function_parameters(
1645             array(
1646                 'assignmentid' => new external_value(PARAM_INT, 'The assignment id to operate on'),
1647                 'userids' => new external_multiple_structure(
1648                     new external_value(PARAM_INT, 'user id'),
1649                     '1 or more user ids',
1650                     VALUE_REQUIRED),
1651                 'dates' => new external_multiple_structure(
1652                     new external_value(PARAM_INT, 'dates'),
1653                     '1 or more extension dates (timestamp)',
1654                     VALUE_REQUIRED),
1655             )
1656         );
1657     }
1659     /**
1660      * Grant extension dates to students for an assignment.
1661      *
1662      * @param int $assignmentid The id of the assignment
1663      * @param array $userids Array of user ids to grant extensions to
1664      * @param array $dates Array of extension dates
1665      * @return array of warnings for each extension date that could not be granted
1666      * @since Moodle 2.6
1667      */
1668     public static function save_user_extensions($assignmentid, $userids, $dates) {
1669         global $CFG;
1671         $params = self::validate_parameters(self::save_user_extensions_parameters(),
1672                         array('assignmentid' => $assignmentid,
1673                               'userids' => $userids,
1674                               'dates' => $dates));
1676         if (count($params['userids']) != count($params['dates'])) {
1677             $detail = 'Length of userids and dates parameters differ.';
1678             $warnings[] = self::generate_warning($params['assignmentid'],
1679                                                  'invalidparameters',
1680                                                  $detail);
1682             return $warnings;
1683         }
1685         list($assignment, $course, $cm, $context) = self::validate_assign($params['assignmentid']);
1687         $warnings = array();
1688         foreach ($params['userids'] as $idx => $userid) {
1689             $duedate = $params['dates'][$idx];
1690             if (!$assignment->save_user_extension($userid, $duedate)) {
1691                 $detail = 'User id: ' . $userid . ', Assignment id: ' . $params['assignmentid'] . ', Extension date: ' . $duedate;
1692                 $warnings[] = self::generate_warning($params['assignmentid'],
1693                                                      'couldnotgrantextensions',
1694                                                      $detail);
1695             }
1696         }
1698         return $warnings;
1699     }
1701     /**
1702      * Describes the return value for save_user_extensions
1703      *
1704      * @return external_single_structure
1705      * @since Moodle 2.6
1706      */
1707     public static function save_user_extensions_returns() {
1708         return new external_warnings();
1709     }
1711     /**
1712      * Describes the parameters for reveal_identities
1713      * @return external_external_function_parameters
1714      * @since  Moodle 2.6
1715      */
1716     public static function reveal_identities_parameters() {
1717         return new external_function_parameters(
1718             array(
1719                 'assignmentid' => new external_value(PARAM_INT, 'The assignment id to operate on')
1720             )
1721         );
1722     }
1724     /**
1725      * Reveal the identities of anonymous students to markers for a single assignment.
1726      *
1727      * @param int $assignmentid The id of the assignment
1728      * @return array of warnings to indicate any errors.
1729      * @since Moodle 2.6
1730      */
1731     public static function reveal_identities($assignmentid) {
1732         global $CFG, $USER;
1734         $params = self::validate_parameters(self::reveal_identities_parameters(),
1735                                             array('assignmentid' => $assignmentid));
1737         list($assignment, $course, $cm, $context) = self::validate_assign($params['assignmentid']);
1739         $warnings = array();
1740         if (!$assignment->reveal_identities()) {
1741             $detail = 'User id: ' . $USER->id . ', Assignment id: ' . $params['assignmentid'];
1742             $warnings[] = self::generate_warning($params['assignmentid'],
1743                                                  'couldnotrevealidentities',
1744                                                  $detail);
1745         }
1747         return $warnings;
1748     }
1750     /**
1751      * Describes the return value for reveal_identities
1752      *
1753      * @return external_single_structure
1754      * @since Moodle 2.6
1755      */
1756     public static function reveal_identities_returns() {
1757         return new external_warnings();
1758     }
1760     /**
1761      * Describes the parameters for save_submission
1762      * @return external_external_function_parameters
1763      * @since  Moodle 2.6
1764      */
1765     public static function save_submission_parameters() {
1766         global $CFG;
1767         $instance = new assign(null, null, null);
1768         $pluginsubmissionparams = array();
1770         foreach ($instance->get_submission_plugins() as $plugin) {
1771             if ($plugin->is_visible()) {
1772                 $pluginparams = $plugin->get_external_parameters();
1773                 if (!empty($pluginparams)) {
1774                     $pluginsubmissionparams = array_merge($pluginsubmissionparams, $pluginparams);
1775                 }
1776             }
1777         }
1779         return new external_function_parameters(
1780             array(
1781                 'assignmentid' => new external_value(PARAM_INT, 'The assignment id to operate on'),
1782                 'plugindata' => new external_single_structure(
1783                     $pluginsubmissionparams
1784                 )
1785             )
1786         );
1787     }
1789     /**
1790      * Save a student submission for a single assignment
1791      *
1792      * @param int $assignmentid The id of the assignment
1793      * @param array $plugindata - The submitted data for plugins
1794      * @return array of warnings to indicate any errors
1795      * @since Moodle 2.6
1796      */
1797     public static function save_submission($assignmentid, $plugindata) {
1798         global $CFG, $USER;
1800         $params = self::validate_parameters(self::save_submission_parameters(),
1801                                             array('assignmentid' => $assignmentid,
1802                                                   'plugindata' => $plugindata));
1804         list($assignment, $course, $cm, $context) = self::validate_assign($params['assignmentid']);
1806         $notices = array();
1808         if (!$assignment->submissions_open($USER->id)) {
1809             $notices[] = get_string('duedatereached', 'assign');
1810         } else {
1811             $submissiondata = (object)$params['plugindata'];
1812             $assignment->save_submission($submissiondata, $notices);
1813         }
1815         $warnings = array();
1816         foreach ($notices as $notice) {
1817             $warnings[] = self::generate_warning($params['assignmentid'],
1818                                                  'couldnotsavesubmission',
1819                                                  $notice);
1820         }
1822         return $warnings;
1823     }
1825     /**
1826      * Describes the return value for save_submission
1827      *
1828      * @return external_single_structure
1829      * @since Moodle 2.6
1830      */
1831     public static function save_submission_returns() {
1832         return new external_warnings();
1833     }
1835     /**
1836      * Describes the parameters for save_grade
1837      * @return external_external_function_parameters
1838      * @since  Moodle 2.6
1839      */
1840     public static function save_grade_parameters() {
1841         global $CFG;
1842         require_once("$CFG->dirroot/grade/grading/lib.php");
1843         $instance = new assign(null, null, null);
1844         $pluginfeedbackparams = array();
1846         foreach ($instance->get_feedback_plugins() as $plugin) {
1847             if ($plugin->is_visible()) {
1848                 $pluginparams = $plugin->get_external_parameters();
1849                 if (!empty($pluginparams)) {
1850                     $pluginfeedbackparams = array_merge($pluginfeedbackparams, $pluginparams);
1851                 }
1852             }
1853         }
1855         $advancedgradingdata = array();
1856         $methods = array_keys(grading_manager::available_methods(false));
1857         foreach ($methods as $method) {
1858             require_once($CFG->dirroot.'/grade/grading/form/'.$method.'/lib.php');
1859             $details  = call_user_func('gradingform_'.$method.'_controller::get_external_instance_filling_details');
1860             if (!empty($details)) {
1861                 $items = array();
1862                 foreach ($details as $key => $value) {
1863                     $value->required = VALUE_OPTIONAL;
1864                     unset($value->content->keys['id']);
1865                     $items[$key] = new external_multiple_structure (new external_single_structure(
1866                         array(
1867                             'criterionid' => new external_value(PARAM_INT, 'criterion id'),
1868                             'fillings' => $value
1869                         )
1870                     ));
1871                 }
1872                 $advancedgradingdata[$method] = new external_single_structure($items, 'items', VALUE_OPTIONAL);
1873             }
1874         }
1876         return new external_function_parameters(
1877             array(
1878                 'assignmentid' => new external_value(PARAM_INT, 'The assignment id to operate on'),
1879                 'userid' => new external_value(PARAM_INT, 'The student id to operate on'),
1880                 'grade' => new external_value(PARAM_FLOAT, 'The new grade for this user. Ignored if advanced grading used'),
1881                 'attemptnumber' => new external_value(PARAM_INT, 'The attempt number (-1 means latest attempt)'),
1882                 'addattempt' => new external_value(PARAM_BOOL, 'Allow another attempt if the attempt reopen method is manual'),
1883                 'workflowstate' => new external_value(PARAM_ALPHA, 'The next marking workflow state'),
1884                 'applytoall' => new external_value(PARAM_BOOL, 'If true, this grade will be applied ' .
1885                                                                'to all members ' .
1886                                                                'of the group (for group assignments).'),
1887                 'plugindata' => new external_single_structure($pluginfeedbackparams, 'plugin data', VALUE_DEFAULT, array()),
1888                 'advancedgradingdata' => new external_single_structure($advancedgradingdata, 'advanced grading data',
1889                                                                        VALUE_DEFAULT, array())
1890             )
1891         );
1892     }
1894     /**
1895      * Save a student grade for a single assignment.
1896      *
1897      * @param int $assignmentid The id of the assignment
1898      * @param int $userid The id of the user
1899      * @param float $grade The grade (ignored if the assignment uses advanced grading)
1900      * @param int $attemptnumber The attempt number
1901      * @param bool $addattempt Allow another attempt
1902      * @param string $workflowstate New workflow state
1903      * @param bool $applytoall Apply the grade to all members of the group
1904      * @param array $plugindata Custom data used by plugins
1905      * @param array $advancedgradingdata Advanced grading data
1906      * @return null
1907      * @since Moodle 2.6
1908      */
1909     public static function save_grade($assignmentid,
1910                                       $userid,
1911                                       $grade,
1912                                       $attemptnumber,
1913                                       $addattempt,
1914                                       $workflowstate,
1915                                       $applytoall,
1916                                       $plugindata = array(),
1917                                       $advancedgradingdata = array()) {
1918         global $CFG, $USER;
1920         $params = self::validate_parameters(self::save_grade_parameters(),
1921                                             array('assignmentid' => $assignmentid,
1922                                                   'userid' => $userid,
1923                                                   'grade' => $grade,
1924                                                   'attemptnumber' => $attemptnumber,
1925                                                   'workflowstate' => $workflowstate,
1926                                                   'addattempt' => $addattempt,
1927                                                   'applytoall' => $applytoall,
1928                                                   'plugindata' => $plugindata,
1929                                                   'advancedgradingdata' => $advancedgradingdata));
1931         list($assignment, $course, $cm, $context) = self::validate_assign($params['assignmentid']);
1933         $gradedata = (object)$params['plugindata'];
1935         $gradedata->addattempt = $params['addattempt'];
1936         $gradedata->attemptnumber = $params['attemptnumber'];
1937         $gradedata->workflowstate = $params['workflowstate'];
1938         $gradedata->applytoall = $params['applytoall'];
1939         $gradedata->grade = $params['grade'];
1941         if (!empty($params['advancedgradingdata'])) {
1942             $advancedgrading = array();
1943             $criteria = reset($params['advancedgradingdata']);
1944             foreach ($criteria as $key => $criterion) {
1945                 $details = array();
1946                 foreach ($criterion as $value) {
1947                     foreach ($value['fillings'] as $filling) {
1948                         $details[$value['criterionid']] = $filling;
1949                     }
1950                 }
1951                 $advancedgrading[$key] = $details;
1952             }
1953             $gradedata->advancedgrading = $advancedgrading;
1954         }
1956         $assignment->save_grade($params['userid'], $gradedata);
1958         return null;
1959     }
1961     /**
1962      * Describes the return value for save_grade
1963      *
1964      * @return external_single_structure
1965      * @since Moodle 2.6
1966      */
1967     public static function save_grade_returns() {
1968         return null;
1969     }
1971     /**
1972      * Describes the parameters for save_grades
1973      * @return external_external_function_parameters
1974      * @since  Moodle 2.7
1975      */
1976     public static function save_grades_parameters() {
1977         global $CFG;
1978         require_once("$CFG->dirroot/grade/grading/lib.php");
1979         $instance = new assign(null, null, null);
1980         $pluginfeedbackparams = array();
1982         foreach ($instance->get_feedback_plugins() as $plugin) {
1983             if ($plugin->is_visible()) {
1984                 $pluginparams = $plugin->get_external_parameters();
1985                 if (!empty($pluginparams)) {
1986                     $pluginfeedbackparams = array_merge($pluginfeedbackparams, $pluginparams);
1987                 }
1988             }
1989         }
1991         $advancedgradingdata = array();
1992         $methods = array_keys(grading_manager::available_methods(false));
1993         foreach ($methods as $method) {
1994             require_once($CFG->dirroot.'/grade/grading/form/'.$method.'/lib.php');
1995             $details  = call_user_func('gradingform_'.$method.'_controller::get_external_instance_filling_details');
1996             if (!empty($details)) {
1997                 $items = array();
1998                 foreach ($details as $key => $value) {
1999                     $value->required = VALUE_OPTIONAL;
2000                     unset($value->content->keys['id']);
2001                     $items[$key] = new external_multiple_structure (new external_single_structure(
2002                         array(
2003                             'criterionid' => new external_value(PARAM_INT, 'criterion id'),
2004                             'fillings' => $value
2005                         )
2006                     ));
2007                 }
2008                 $advancedgradingdata[$method] = new external_single_structure($items, 'items', VALUE_OPTIONAL);
2009             }
2010         }
2012         return new external_function_parameters(
2013             array(
2014                 'assignmentid' => new external_value(PARAM_INT, 'The assignment id to operate on'),
2015                 'applytoall' => new external_value(PARAM_BOOL, 'If true, this grade will be applied ' .
2016                                                                'to all members ' .
2017                                                                'of the group (for group assignments).'),
2018                 'grades' => new external_multiple_structure(
2019                     new external_single_structure(
2020                         array (
2021                             'userid' => new external_value(PARAM_INT, 'The student id to operate on'),
2022                             'grade' => new external_value(PARAM_FLOAT, 'The new grade for this user. '.
2023                                                                        'Ignored if advanced grading used'),
2024                             'attemptnumber' => new external_value(PARAM_INT, 'The attempt number (-1 means latest attempt)'),
2025                             'addattempt' => new external_value(PARAM_BOOL, 'Allow another attempt if manual attempt reopen method'),
2026                             'workflowstate' => new external_value(PARAM_ALPHA, 'The next marking workflow state'),
2027                             'plugindata' => new external_single_structure($pluginfeedbackparams, 'plugin data',
2028                                                                           VALUE_DEFAULT, array()),
2029                             'advancedgradingdata' => new external_single_structure($advancedgradingdata, 'advanced grading data',
2030                                                                                    VALUE_DEFAULT, array())
2031                         )
2032                     )
2033                 )
2034             )
2035         );
2036     }
2038     /**
2039      * Save multiple student grades for a single assignment.
2040      *
2041      * @param int $assignmentid The id of the assignment
2042      * @param boolean $applytoall If set to true and this is a team assignment,
2043      * apply the grade to all members of the group
2044      * @param array $grades grade data for one or more students that includes
2045      *                  userid - The id of the student being graded
2046      *                  grade - The grade (ignored if the assignment uses advanced grading)
2047      *                  attemptnumber - The attempt number
2048      *                  addattempt - Allow another attempt
2049      *                  workflowstate - New workflow state
2050      *                  plugindata - Custom data used by plugins
2051      *                  advancedgradingdata - Optional Advanced grading data
2052      * @throws invalid_parameter_exception if multiple grades are supplied for
2053      * a team assignment that has $applytoall set to true
2054      * @return null
2055      * @since Moodle 2.7
2056      */
2057     public static function save_grades($assignmentid, $applytoall = false, $grades) {
2058         global $CFG, $USER;
2060         $params = self::validate_parameters(self::save_grades_parameters(),
2061                                             array('assignmentid' => $assignmentid,
2062                                                   'applytoall' => $applytoall,
2063                                                   'grades' => $grades));
2065         list($assignment, $course, $cm, $context) = self::validate_assign($params['assignmentid']);
2067         if ($assignment->get_instance()->teamsubmission && $params['applytoall']) {
2068             // Check that only 1 user per submission group is provided.
2069             $groupids = array();
2070             foreach ($params['grades'] as $gradeinfo) {
2071                 $group = $assignment->get_submission_group($gradeinfo['userid']);
2072                 if (in_array($group->id, $groupids)) {
2073                     throw new invalid_parameter_exception('Multiple grades for the same team have been supplied '
2074                                                           .' this is not permitted when the applytoall flag is set');
2075                 } else {
2076                     $groupids[] = $group->id;
2077                 }
2078             }
2079         }
2081         foreach ($params['grades'] as $gradeinfo) {
2082             $gradedata = (object)$gradeinfo['plugindata'];
2083             $gradedata->addattempt = $gradeinfo['addattempt'];
2084             $gradedata->attemptnumber = $gradeinfo['attemptnumber'];
2085             $gradedata->workflowstate = $gradeinfo['workflowstate'];
2086             $gradedata->applytoall = $params['applytoall'];
2087             $gradedata->grade = $gradeinfo['grade'];
2089             if (!empty($gradeinfo['advancedgradingdata'])) {
2090                 $advancedgrading = array();
2091                 $criteria = reset($gradeinfo['advancedgradingdata']);
2092                 foreach ($criteria as $key => $criterion) {
2093                     $details = array();
2094                     foreach ($criterion as $value) {
2095                         foreach ($value['fillings'] as $filling) {
2096                             $details[$value['criterionid']] = $filling;
2097                         }
2098                     }
2099                     $advancedgrading[$key] = $details;
2100                 }
2101                 $gradedata->advancedgrading = $advancedgrading;
2102             }
2103             $assignment->save_grade($gradeinfo['userid'], $gradedata);
2104         }
2106         return null;
2107     }
2109     /**
2110      * Describes the return value for save_grades
2111      *
2112      * @return external_single_structure
2113      * @since Moodle 2.7
2114      */
2115     public static function save_grades_returns() {
2116         return null;
2117     }
2119     /**
2120      * Describes the parameters for copy_previous_attempt
2121      * @return external_function_parameters
2122      * @since  Moodle 2.6
2123      */
2124     public static function copy_previous_attempt_parameters() {
2125         return new external_function_parameters(
2126             array(
2127                 'assignmentid' => new external_value(PARAM_INT, 'The assignment id to operate on'),
2128             )
2129         );
2130     }
2132     /**
2133      * Copy a students previous attempt to a new attempt.
2134      *
2135      * @param int $assignmentid
2136      * @return array of warnings to indicate any errors.
2137      * @since Moodle 2.6
2138      */
2139     public static function copy_previous_attempt($assignmentid) {
2141         $params = self::validate_parameters(self::copy_previous_attempt_parameters(),
2142                                             array('assignmentid' => $assignmentid));
2144         list($assignment, $course, $cm, $context) = self::validate_assign($params['assignmentid']);
2146         $notices = array();
2148         $assignment->copy_previous_attempt($notices);
2150         $warnings = array();
2151         foreach ($notices as $notice) {
2152             $warnings[] = self::generate_warning($assignmentid,
2153                                                  'couldnotcopyprevioussubmission',
2154                                                  $notice);
2155         }
2157         return $warnings;
2158     }
2160     /**
2161      * Describes the return value for save_submission
2162      *
2163      * @return external_single_structure
2164      * @since Moodle 2.6
2165      */
2166     public static function copy_previous_attempt_returns() {
2167         return new external_warnings();
2168     }
2170     /**
2171      * Returns description of method parameters
2172      *
2173      * @return external_function_parameters
2174      * @since Moodle 3.0
2175      */
2176     public static function view_grading_table_parameters() {
2177         return new external_function_parameters(
2178             array(
2179                 'assignid' => new external_value(PARAM_INT, 'assign instance id')
2180             )
2181         );
2182     }
2184     /**
2185      * Trigger the grading_table_viewed event.
2186      *
2187      * @param int $assignid the assign instance id
2188      * @return array of warnings and status result
2189      * @since Moodle 3.0
2190      * @throws moodle_exception
2191      */
2192     public static function view_grading_table($assignid) {
2194         $params = self::validate_parameters(self::view_grading_table_parameters(),
2195                                             array(
2196                                                 'assignid' => $assignid
2197                                             ));
2198         $warnings = array();
2200         list($assign, $course, $cm, $context) = self::validate_assign($params['assignid']);
2202         $assign->require_view_grades();
2203         \mod_assign\event\grading_table_viewed::create_from_assign($assign)->trigger();
2205         $result = array();
2206         $result['status'] = true;
2207         $result['warnings'] = $warnings;
2208         return $result;
2209     }
2211     /**
2212      * Returns description of method result value
2213      *
2214      * @return external_description
2215      * @since Moodle 3.0
2216      */
2217     public static function view_grading_table_returns() {
2218         return new external_single_structure(
2219             array(
2220                 'status' => new external_value(PARAM_BOOL, 'status: true if success'),
2221                 'warnings' => new external_warnings()
2222             )
2223         );
2224     }
2226     /**
2227      * Describes the parameters for view_submission_status.
2228      *
2229      * @return external_external_function_parameters
2230      * @since Moodle 3.1
2231      */
2232     public static function view_submission_status_parameters() {
2233         return new external_function_parameters (
2234             array(
2235                 'assignid' => new external_value(PARAM_INT, 'assign instance id'),
2236             )
2237         );
2238     }
2240     /**
2241      * Trigger the submission status viewed event.
2242      *
2243      * @param int $assignid assign instance id
2244      * @return array of warnings and status result
2245      * @since Moodle 3.1
2246      */
2247     public static function view_submission_status($assignid) {
2249         $warnings = array();
2250         $params = array(
2251             'assignid' => $assignid,
2252         );
2253         $params = self::validate_parameters(self::view_submission_status_parameters(), $params);
2255         list($assign, $course, $cm, $context) = self::validate_assign($params['assignid']);
2257         \mod_assign\event\submission_status_viewed::create_from_assign($assign)->trigger();
2259         $result = array();
2260         $result['status'] = true;
2261         $result['warnings'] = $warnings;
2262         return $result;
2263     }
2265     /**
2266      * Describes the view_submission_status return value.
2267      *
2268      * @return external_single_structure
2269      * @since Moodle 3.1
2270      */
2271     public static function view_submission_status_returns() {
2272         return new external_single_structure(
2273             array(
2274                 'status' => new external_value(PARAM_BOOL, 'status: true if success'),
2275                 'warnings' => new external_warnings(),
2276             )
2277         );
2278     }
2280     /**
2281      * Describes the parameters for get_submission_status.
2282      *
2283      * @return external_external_function_parameters
2284      * @since Moodle 3.1
2285      */
2286     public static function get_submission_status_parameters() {
2287         return new external_function_parameters (
2288             array(
2289                 'assignid' => new external_value(PARAM_INT, 'assignment instance id'),
2290                 'userid' => new external_value(PARAM_INT, 'user id (empty for current user)', VALUE_DEFAULT, 0),
2291             )
2292         );
2293     }
2295     /**
2296      * Returns information about an assignment submission status for a given user.
2297      *
2298      * @param int $assignid assignment instance id
2299      * @param int $userid user id (empty for current user)
2300      * @return array of warnings and grading, status, feedback and previous attempts information
2301      * @since Moodle 3.1
2302      * @throws required_capability_exception
2303      */
2304     public static function get_submission_status($assignid, $userid = 0) {
2305         global $USER;
2307         $warnings = array();
2309         $params = array(
2310             'assignid' => $assignid,
2311             'userid' => $userid,
2312         );
2313         $params = self::validate_parameters(self::get_submission_status_parameters(), $params);
2315         list($assign, $course, $cm, $context) = self::validate_assign($params['assignid']);
2317         // Default value for userid.
2318         if (empty($params['userid'])) {
2319             $params['userid'] = $USER->id;
2320         }
2321         $user = core_user::get_user($params['userid'], '*', MUST_EXIST);
2322         core_user::require_active_user($user);
2324         if (!$assign->can_view_submission($user->id)) {
2325             throw new required_capability_exception($context, 'mod/assign:viewgrades', 'nopermission', '');
2326         }
2328         $gradingsummary = $lastattempt = $feedback = $previousattempts = null;
2330         // Get the renderable since it contais all the info we need.
2331         if ($assign->can_view_grades()) {
2332             $gradingsummary = $assign->get_assign_grading_summary_renderable();
2333         }
2335         // Retrieve the rest of the renderable objects.
2336         if (has_capability('mod/assign:submit', $assign->get_context(), $user)) {
2337             $lastattempt = $assign->get_assign_submission_status_renderable($user, true);
2338         }
2340         $feedback = $assign->get_assign_feedback_status_renderable($user);
2342         $previousattempts = $assign->get_assign_attempt_history_renderable($user);
2344         // Now, build the result.
2345         $result = array();
2347         // First of all, grading summary, this is suitable for teachers/managers.
2348         if ($gradingsummary) {
2349             $result['gradingsummary'] = $gradingsummary;
2350         }
2352         // Did we submit anything?
2353         if ($lastattempt) {
2354             $submissionplugins = $assign->get_submission_plugins();
2356             if (empty($lastattempt->submission)) {
2357                 unset($lastattempt->submission);
2358             } else {
2359                 $lastattempt->submission->plugins = self::get_plugins_data($assign, $submissionplugins, $lastattempt->submission);
2360             }
2362             if (empty($lastattempt->teamsubmission)) {
2363                 unset($lastattempt->teamsubmission);
2364             } else {
2365                 $lastattempt->teamsubmission->plugins = self::get_plugins_data($assign, $submissionplugins,
2366                                                                                 $lastattempt->teamsubmission);
2367             }
2369             // We need to change the type of some of the structures retrieved from the renderable.
2370             if (!empty($lastattempt->submissiongroup)) {
2371                 $lastattempt->submissiongroup = $lastattempt->submissiongroup->id;
2372             } else {
2373                 unset($lastattempt->submissiongroup);
2374             }
2376             if (!empty($lastattempt->usergroups)) {
2377                 $lastattempt->usergroups = array_keys($lastattempt->usergroups);
2378             }
2379             // We cannot use array_keys here.
2380             if (!empty($lastattempt->submissiongroupmemberswhoneedtosubmit)) {
2381                 $lastattempt->submissiongroupmemberswhoneedtosubmit = array_map(
2382                                                                             function($e){
2383                                                                                 return $e->id;
2384                                                                             },
2385                                                                             $lastattempt->submissiongroupmemberswhoneedtosubmit);
2386             }
2388             $result['lastattempt'] = $lastattempt;
2389         }
2391         // The feedback for our latest submission.
2392         if ($feedback) {
2393             if ($feedback->grade) {
2394                 $feedbackplugins = $assign->get_feedback_plugins();
2395                 $feedback->plugins = self::get_plugins_data($assign, $feedbackplugins, $feedback->grade);
2396             } else {
2397                 unset($feedback->plugins);
2398                 unset($feedback->grade);
2399             }
2401             $result['feedback'] = $feedback;
2402         }
2404         // Retrieve only previous attempts.
2405         if ($previousattempts and count($previousattempts->submissions) > 1) {
2406             // Don't show the last one because it is the current submission.
2407             array_pop($previousattempts->submissions);
2409             // Show newest to oldest.
2410             $previousattempts->submissions = array_reverse($previousattempts->submissions);
2412             foreach ($previousattempts->submissions as $i => $submission) {
2413                 $attempt = array();
2415                 $grade = null;
2416                 foreach ($previousattempts->grades as $onegrade) {
2417                     if ($onegrade->attemptnumber == $submission->attemptnumber) {
2418                         $grade = $onegrade;
2419                         break;
2420                     }
2421                 }
2423                 $attempt['attemptnumber'] = $submission->attemptnumber;
2425                 if ($submission) {
2426                     $submission->plugins = self::get_plugins_data($assign, $previousattempts->submissionplugins, $submission);
2427                     $attempt['submission'] = $submission;
2428                 }
2430                 if ($grade) {
2431                     // From object to id.
2432                     $grade->grader = $grade->grader->id;
2433                     $feedbackplugins = self::get_plugins_data($assign, $previousattempts->feedbackplugins, $grade);
2435                     $attempt['grade'] = $grade;
2436                     $attempt['feedbackplugins'] = $feedbackplugins;
2437                 }
2438                 $result['previousattempts'][] = $attempt;
2439             }
2440         }
2442         $result['warnings'] = $warnings;
2443         return $result;
2444     }
2446     /**
2447      * Describes the get_submission_status return value.
2448      *
2449      * @return external_single_structure
2450      * @since Moodle 3.1
2451      */
2452     public static function get_submission_status_returns() {
2453         return new external_single_structure(
2454             array(
2455                 'gradingsummary' => new external_single_structure(
2456                     array(
2457                         'participantcount' => new external_value(PARAM_INT, 'Number of users who can submit.'),
2458                         'submissiondraftscount' => new external_value(PARAM_INT, 'Number of submissions in draft status.'),
2459                         'submissiondraftscount' => new external_value(PARAM_INT, 'Number of submissions in draft status.'),
2460                         'submissionsenabled' => new external_value(PARAM_BOOL, 'Whether submissions are enabled or not.'),
2461                         'submissionssubmittedcount' => new external_value(PARAM_INT, 'Number of submissions in submitted status.'),
2462                         'submissionsneedgradingcount' => new external_value(PARAM_INT, 'Number of submissions that need grading.'),
2463                         'warnofungroupedusers' => new external_value(PARAM_BOOL, 'Whether we need to warn people that there
2464                                                                         are users without groups.'),
2465                     ), 'Grading information.', VALUE_OPTIONAL
2466                 ),
2467                 'lastattempt' => new external_single_structure(
2468                     array(
2469                         'submission' => self::get_submission_structure(VALUE_OPTIONAL),
2470                         'teamsubmission' => self::get_submission_structure(VALUE_OPTIONAL),
2471                         'submissiongroup' => new external_value(PARAM_INT, 'The submission group id (for group submissions only).',
2472                                                                 VALUE_OPTIONAL),
2473                         'submissiongroupmemberswhoneedtosubmit' => new external_multiple_structure(
2474                             new external_value(PARAM_INT, 'USER id.'),
2475                             'List of users who still need to submit (for group submissions only).',
2476                             VALUE_OPTIONAL
2477                         ),
2478                         'submissionsenabled' => new external_value(PARAM_BOOL, 'Whether submissions are enabled or not.'),
2479                         'locked' => new external_value(PARAM_BOOL, 'Whether new submissions are locked.'),
2480                         'graded' => new external_value(PARAM_BOOL, 'Whether the submission is graded.'),
2481                         'canedit' => new external_value(PARAM_BOOL, 'Whether the user can edit the current submission.'),
2482                         'cansubmit' => new external_value(PARAM_BOOL, 'Whether the user can submit.'),
2483                         'extensionduedate' => new external_value(PARAM_INT, 'Extension due date.'),
2484                         'blindmarking' => new external_value(PARAM_BOOL, 'Whether blind marking is enabled.'),
2485                         'gradingstatus' => new external_value(PARAM_ALPHANUMEXT, 'Grading status.'),
2486                         'usergroups' => new external_multiple_structure(
2487                             new external_value(PARAM_INT, 'Group id.'), 'User groups in the course.'
2488                         ),
2489                     ), 'Last attempt information.', VALUE_OPTIONAL
2490                 ),
2491                 'feedback' => new external_single_structure(
2492                     array(
2493                         'grade' => self::get_grade_structure(VALUE_OPTIONAL),
2494                         'gradefordisplay' => new external_value(PARAM_RAW, 'Grade rendered into a format suitable for display.'),
2495                         'gradeddate' => new external_value(PARAM_INT, 'The date the user was graded.'),
2496                         'plugins' => new external_multiple_structure(self::get_plugin_structure(), 'Plugins info.', VALUE_OPTIONAL),
2497                     ), 'Feedback for the last attempt.', VALUE_OPTIONAL
2498                 ),
2499                 'previousattempts' => new external_multiple_structure(
2500                     new external_single_structure(
2501                         array(
2502                             'attemptnumber' => new external_value(PARAM_INT, 'Attempt number.'),
2503                             'submission' => self::get_submission_structure(VALUE_OPTIONAL),
2504                             'grade' => self::get_grade_structure(VALUE_OPTIONAL),
2505                             'feedbackplugins' => new external_multiple_structure(self::get_plugin_structure(), 'Feedback info.',
2506                                                                                     VALUE_OPTIONAL),
2507                         )
2508                     ), 'List all the previous attempts did by the user.', VALUE_OPTIONAL
2509                 ),
2510                 'warnings' => new external_warnings(),
2511             )
2512         );
2513     }
2515     /**
2516      * Returns description of method parameters
2517      *
2518      * @return external_function_parameters
2519      * @since Moodle 3.1
2520      */
2521     public static function list_participants_parameters() {
2522         return new external_function_parameters(
2523             array(
2524                 'assignid' => new external_value(PARAM_INT, 'assign instance id'),
2525                 'groupid' => new external_value(PARAM_INT, 'group id'),
2526                 'filter' => new external_value(PARAM_RAW, 'search string to filter the results'),
2527                 'skip' => new external_value(PARAM_INT, 'number of records to skip', VALUE_DEFAULT, 0),
2528                 'limit' => new external_value(PARAM_INT, 'maximum number of records to return', VALUE_DEFAULT, 0),
2529                 'onlyids' => new external_value(PARAM_BOOL, 'Do not return all user fields', VALUE_DEFAULT, false),
2530             )
2531         );
2532     }
2534     /**
2535      * Retrieves the list of students to be graded for the assignment.
2536      *
2537      * @param int $assignid the assign instance id
2538      * @param int $groupid the current group id
2539      * @param string $filter search string to filter the results.
2540      * @param int $skip Number of records to skip
2541      * @param int $limit Maximum number of records to return
2542      * @return array of warnings and status result
2543      * @since Moodle 3.1
2544      * @throws moodle_exception
2545      */
2546     public static function list_participants($assignid, $groupid, $filter, $skip, $limit) {
2547         global $DB, $CFG;
2548         require_once($CFG->dirroot . "/mod/assign/locallib.php");
2549         require_once($CFG->dirroot . "/user/lib.php");
2551         $params = self::validate_parameters(self::list_participants_parameters(),
2552                                             array(
2553                                                 'assignid' => $assignid,
2554                                                 'groupid' => $groupid,
2555                                                 'filter' => $filter,
2556                                                 'skip' => $skip,
2557                                                 'limit' => $limit
2558                                             ));
2559         $warnings = array();
2561         list($assign, $course, $cm, $context) = self::validate_assign($params['assignid']);
2563         require_capability('mod/assign:view', $context);
2565         $assign->require_view_grades();
2567         $participants = $assign->list_participants_with_filter_status_and_group($params['groupid']);
2569         $result = array();
2570         $index = 0;
2571         foreach ($participants as $record) {
2572             // Preserve the fullname set by the assignment.
2573             $fullname = $record->fullname;
2574             $searchable = $fullname;
2575             $match = false;
2576             if (empty($filter)) {
2577                 $match = true;
2578             } else {
2579                 $filter = core_text::strtolower($filter);
2580                 $value = core_text::strtolower($searchable);
2581                 if (is_string($value) && (core_text::strpos($value, $filter) !== false)) {
2582                     $match = true;
2583                 }
2584             }
2585             if ($match) {
2586                 $index++;
2587                 if ($index <= $params['skip']) {
2588                     continue;
2589                 }
2590                 if (($params['limit'] > 0) && (($index - $params['skip']) > $params['limit'])) {
2591                     break;
2592                 }
2593                 // Now we do the expensive lookup of user details because we completed the filtering.
2594                 if (!$assign->is_blind_marking() && !$params['onlyids']) {
2595                     $userdetails = user_get_user_details($record, $course);
2596                 } else {
2597                     $userdetails = array('id' => $record->id);
2598                 }
2599                 $userdetails['fullname'] = $fullname;
2600                 $userdetails['submitted'] = $record->submitted;
2601                 $userdetails['requiregrading'] = $record->requiregrading;
2602                 if (!empty($record->groupid)) {
2603                     $userdetails['groupid'] = $record->groupid;
2604                 }
2605                 if (!empty($record->groupname)) {
2606                     $userdetails['groupname'] = $record->groupname;
2607                 }
2609                 $result[] = $userdetails;
2610             }
2611         }
2612         return $result;
2613     }
2615     /**
2616      * Returns the description of the results of the mod_assign_external::list_participants() method.
2617      *
2618      * @return external_description
2619      * @since Moodle 3.1
2620      */
2621     public static function list_participants_returns() {
2622         // Get user description.
2623         $userdesc = core_user_external::user_description();
2624         // List unneeded properties.
2625         $unneededproperties = [
2626             'auth', 'confirmed', 'lang', 'calendartype', 'theme', 'timezone', 'mailformat'
2627         ];
2628         // Remove unneeded properties for consistency with the previous version.
2629         foreach ($unneededproperties as $prop) {
2630             unset($userdesc->keys[$prop]);
2631         }
2633         // Override property attributes for consistency with the previous version.
2634         $userdesc->keys['fullname']->type = PARAM_NOTAGS;
2635         $userdesc->keys['profileimageurlsmall']->required = VALUE_OPTIONAL;
2636         $userdesc->keys['profileimageurl']->required = VALUE_OPTIONAL;
2637         $userdesc->keys['email']->desc = 'Email address';
2638         $userdesc->keys['email']->desc = 'Email address';
2639         $userdesc->keys['idnumber']->desc = 'The idnumber of the user';
2641         // Define other keys.
2642         $otherkeys = [
2643             'groups' => new external_multiple_structure(
2644                 new external_single_structure(
2645                     [
2646                         'id' => new external_value(PARAM_INT, 'group id'),
2647                         'name' => new external_value(PARAM_RAW, 'group name'),
2648                         'description' => new external_value(PARAM_RAW, 'group description'),
2649                     ]
2650                 ), 'user groups', VALUE_OPTIONAL
2651             ),
2652             'roles' => new external_multiple_structure(
2653                 new external_single_structure(
2654                     [
2655                         'roleid' => new external_value(PARAM_INT, 'role id'),
2656                         'name' => new external_value(PARAM_RAW, 'role name'),
2657                         'shortname' => new external_value(PARAM_ALPHANUMEXT, 'role shortname'),
2658                         'sortorder' => new external_value(PARAM_INT, 'role sortorder')
2659                     ]
2660                 ), 'user roles', VALUE_OPTIONAL
2661             ),
2662             'enrolledcourses' => new external_multiple_structure(
2663                 new external_single_structure(
2664                     [
2665                         'id' => new external_value(PARAM_INT, 'Id of the course'),
2666                         'fullname' => new external_value(PARAM_RAW, 'Fullname of the course'),
2667                         'shortname' => new external_value(PARAM_RAW, 'Shortname of the course')
2668                     ]
2669                 ), 'Courses where the user is enrolled - limited by which courses the user is able to see', VALUE_OPTIONAL
2670             ),
2671             'submitted' => new external_value(PARAM_BOOL, 'have they submitted their assignment'),
2672             'requiregrading' => new external_value(PARAM_BOOL, 'is their submission waiting for grading'),
2673             'groupid' => new external_value(PARAM_INT, 'for group assignments this is the group id', VALUE_OPTIONAL),
2674             'groupname' => new external_value(PARAM_NOTAGS, 'for group assignments this is the group name', VALUE_OPTIONAL),
2675         ];
2677         // Merge keys.
2678         $userdesc->keys = array_merge($userdesc->keys, $otherkeys);
2679         return new external_multiple_structure($userdesc);
2680     }
2682     /**
2683      * Returns description of method parameters
2684      *
2685      * @return external_function_parameters
2686      * @since Moodle 3.1
2687      */
2688     public static function get_participant_parameters() {
2689         return new external_function_parameters(
2690             array(
2691                 'assignid' => new external_value(PARAM_INT, 'assign instance id'),
2692                 'userid' => new external_value(PARAM_INT, 'user id'),
2693                 'embeduser' => new external_value(PARAM_BOOL, 'user id', VALUE_DEFAULT, false),
2694             )
2695         );
2696     }
2698     /**
2699      * Get the user participating in the given assignment. An error with code 'usernotincourse'
2700      * is thrown is the user isn't a participant of the given assignment.
2701      *
2702      * @param int $assignid the assign instance id
2703      * @param int $userid the user id
2704      * @param bool $embeduser return user details (only applicable if not blind marking)
2705      * @return array of warnings and status result
2706      * @since Moodle 3.1
2707      * @throws moodle_exception
2708      */
2709     public static function get_participant($assignid, $userid, $embeduser) {
2710         global $DB, $CFG;
2711         require_once($CFG->dirroot . "/mod/assign/locallib.php");
2712         require_once($CFG->dirroot . "/user/lib.php");
2714         $params = self::validate_parameters(self::get_participant_parameters(), array(
2715             'assignid' => $assignid,
2716             'userid' => $userid,
2717             'embeduser' => $embeduser
2718         ));
2720         list($assign, $course, $cm, $context) = self::validate_assign($params['assignid']);
2721         $assign->require_view_grades();
2723         $participant = $assign->get_participant($params['userid']);
2724         if (!$participant) {
2725             // No participant found so we can return early.
2726             throw new moodle_exception('usernotincourse');
2727         }
2729         $return = array(
2730             'id' => $participant->id,
2731             'fullname' => $participant->fullname,
2732             'submitted' => $participant->submitted,
2733             'requiregrading' => $participant->requiregrading,
2734             'blindmarking' => $assign->is_blind_marking(),
2735         );
2737         if (!empty($participant->groupid)) {
2738             $return['groupid'] = $participant->groupid;
2739         }
2740         if (!empty($participant->groupname)) {
2741             $return['groupname'] = $participant->groupname;
2742         }
2744         // Skip the expensive lookup of user detail if we're blind marking or the caller
2745         // hasn't asked for user details to be embedded.
2746         if (!$assign->is_blind_marking() && $embeduser) {
2747             $return['user'] = user_get_user_details($participant, $course);
2748         }
2750         return $return;
2751     }
2753     /**
2754      * Returns description of method result value
2755      *
2756      * @return external_description
2757      * @since Moodle 3.1
2758      */
2759     public static function get_participant_returns() {
2760         $userdescription = core_user_external::user_description();
2761         $userdescription->default = [];
2762         $userdescription->required = VALUE_OPTIONAL;
2764         return new external_single_structure(array(
2765             'id' => new external_value(PARAM_INT, 'ID of the user'),
2766             'fullname' => new external_value(PARAM_NOTAGS, 'The fullname of the user'),
2767             'submitted' => new external_value(PARAM_BOOL, 'have they submitted their assignment'),
2768             'requiregrading' => new external_value(PARAM_BOOL, 'is their submission waiting for grading'),
2769             'blindmarking' => new external_value(PARAM_BOOL, 'is blind marking enabled for this assignment'),
2770             'groupid' => new external_value(PARAM_INT, 'for group assignments this is the group id', VALUE_OPTIONAL),
2771             'groupname' => new external_value(PARAM_NOTAGS, 'for group assignments this is the group name', VALUE_OPTIONAL),
2772             'user' => $userdescription,
2773         ));
2774     }
2776     /**
2777      * Utility function for validating an assign.
2778      *
2779      * @param int $assignid assign instance id
2780      * @return array array containing the assign, course, context and course module objects
2781      * @since  Moodle 3.2
2782      */
2783     protected static function validate_assign($assignid) {
2784         global $DB;
2786         // Request and permission validation.
2787         $assign = $DB->get_record('assign', array('id' => $assignid), 'id', MUST_EXIST);
2788         list($course, $cm) = get_course_and_cm_from_instance($assign, 'assign');
2790         $context = context_module::instance($cm->id);
2791         // Please, note that is not required to check mod/assign:view because is done by validate_context->require_login.
2792         self::validate_context($context);
2793         $assign = new assign($context, $cm, $course);
2795         return array($assign, $course, $cm, $context);
2796     }
2798     /**
2799      * Describes the parameters for view_assign.
2800      *
2801      * @return external_external_function_parameters
2802      * @since Moodle 3.2
2803      */
2804     public static function view_assign_parameters() {
2805         return new external_function_parameters (
2806             array(
2807                 'assignid' => new external_value(PARAM_INT, 'assign instance id'),
2808             )
2809         );
2810     }
2812     /**
2813      * Update the module completion status.
2814      *
2815      * @param int $assignid assign instance id
2816      * @return array of warnings and status result
2817      * @since Moodle 3.2
2818      */
2819     public static function view_assign($assignid) {
2820         $warnings = array();
2821         $params = array(
2822             'assignid' => $assignid,
2823         );
2824         $params = self::validate_parameters(self::view_assign_parameters(), $params);
2826         list($assign, $course, $cm, $context) = self::validate_assign($params['assignid']);
2828         $assign->set_module_viewed();
2830         $result = array();
2831         $result['status'] = true;
2832         $result['warnings'] = $warnings;
2833         return $result;
2834     }
2836     /**
2837      * Describes the view_assign return value.
2838      *
2839      * @return external_single_structure
2840      * @since Moodle 3.2
2841      */
2842     public static function view_assign_returns() {
2843         return new external_single_structure(
2844             array(
2845                 'status' => new external_value(PARAM_BOOL, 'status: true if success'),
2846                 'warnings' => new external_warnings(),
2847             )
2848         );
2849     }