MDL-42266 Lib: Allow additional max upload file sizes
[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                     }
405                     $assign = new assign($context, null, null);
406                     // Update assign with override information.
407                     $assign->update_effective_access($USER->id);
409                     // Get configurations for only enabled plugins.
410                     $plugins = $assign->get_submission_plugins();
411                     $plugins = array_merge($plugins, $assign->get_feedback_plugins());
413                     $configarray = array();
414                     foreach ($plugins as $plugin) {
415                         if ($plugin->is_enabled() && $plugin->is_visible()) {
416                             $configrecords = $plugin->get_config_for_external();
417                             foreach ($configrecords as $name => $value) {
418                                 $configarray[] = array(
419                                     'plugin' => $plugin->get_type(),
420                                     'subtype' => $plugin->get_subtype(),
421                                     'name' => $name,
422                                     'value' => $value
423                                 );
424                             }
425                         }
426                     }
428                     $assignment = array(
429                         'id' => $module->assignmentid,
430                         'cmid' => $module->id,
431                         'course' => $module->course,
432                         'name' => $module->name,
433                         'nosubmissions' => $module->nosubmissions,
434                         'submissiondrafts' => $module->submissiondrafts,
435                         'sendnotifications' => $module->sendnotifications,
436                         'sendlatenotifications' => $module->sendlatenotifications,
437                         'sendstudentnotifications' => $module->sendstudentnotifications,
438                         'duedate' => $assign->get_instance()->duedate,
439                         'allowsubmissionsfromdate' => $assign->get_instance()->allowsubmissionsfromdate,
440                         'grade' => $module->grade,
441                         'timemodified' => $module->timemodified,
442                         'completionsubmit' => $module->completionsubmit,
443                         'cutoffdate' => $assign->get_instance()->cutoffdate,
444                         'teamsubmission' => $module->teamsubmission,
445                         'requireallteammemberssubmit' => $module->requireallteammemberssubmit,
446                         'teamsubmissiongroupingid' => $module->teamsubmissiongroupingid,
447                         'blindmarking' => $module->blindmarking,
448                         'revealidentities' => $module->revealidentities,
449                         'attemptreopenmethod' => $module->attemptreopenmethod,
450                         'maxattempts' => $module->maxattempts,
451                         'markingworkflow' => $module->markingworkflow,
452                         'markingallocation' => $module->markingallocation,
453                         'requiresubmissionstatement' => $module->requiresubmissionstatement,
454                         'preventsubmissionnotingroup' => $module->preventsubmissionnotingroup,
455                         'configs' => $configarray
456                     );
458                     // Return or not intro and file attachments depending on the plugin settings.
459                     if ($assign->show_intro()) {
461                         list($assignment['intro'], $assignment['introformat']) = external_format_text($module->intro,
462                             $module->introformat, $context->id, 'mod_assign', 'intro', null);
463                         $assignment['introfiles'] = external_util::get_area_files($context->id, 'mod_assign', 'intro', false,
464                                                                                     false);
466                         $assignment['introattachments'] = external_util::get_area_files($context->id, 'mod_assign',
467                                                             ASSIGN_INTROATTACHMENT_FILEAREA, 0);
468                     }
470                     if ($module->requiresubmissionstatement) {
471                         // Submission statement is required, return the submission statement value.
472                         $adminconfig = get_config('assign');
473                         list($assignment['submissionstatement'], $assignment['submissionstatementformat']) = external_format_text(
474                                 $adminconfig->submissionstatement, FORMAT_MOODLE, $context->id, 'mod_assign', '', 0);
475                     }
477                     $assignmentarray[] = $assignment;
478                 }
479             }
480             $coursearray[]= array(
481                 'id' => $courses[$id]->id,
482                 'fullname' => external_format_string($courses[$id]->fullname, $course->contextid),
483                 'shortname' => external_format_string($courses[$id]->shortname, $course->contextid),
484                 'timemodified' => $courses[$id]->timemodified,
485                 'assignments' => $assignmentarray
486             );
487         }
489         $result = array(
490             'courses' => $coursearray,
491             'warnings' => $warnings
492         );
493         return $result;
494     }
496     /**
497      * Creates an assignment external_single_structure
498      *
499      * @return external_single_structure
500      * @since Moodle 2.4
501      */
502     private static function get_assignments_assignment_structure() {
503         return new external_single_structure(
504             array(
505                 'id' => new external_value(PARAM_INT, 'assignment id'),
506                 'cmid' => new external_value(PARAM_INT, 'course module id'),
507                 'course' => new external_value(PARAM_INT, 'course id'),
508                 'name' => new external_value(PARAM_TEXT, 'assignment name'),
509                 'nosubmissions' => new external_value(PARAM_INT, 'no submissions'),
510                 'submissiondrafts' => new external_value(PARAM_INT, 'submissions drafts'),
511                 'sendnotifications' => new external_value(PARAM_INT, 'send notifications'),
512                 'sendlatenotifications' => new external_value(PARAM_INT, 'send notifications'),
513                 'sendstudentnotifications' => new external_value(PARAM_INT, 'send student notifications (default)'),
514                 'duedate' => new external_value(PARAM_INT, 'assignment due date'),
515                 'allowsubmissionsfromdate' => new external_value(PARAM_INT, 'allow submissions from date'),
516                 'grade' => new external_value(PARAM_INT, 'grade type'),
517                 'timemodified' => new external_value(PARAM_INT, 'last time assignment was modified'),
518                 'completionsubmit' => new external_value(PARAM_INT, 'if enabled, set activity as complete following submission'),
519                 'cutoffdate' => new external_value(PARAM_INT, 'date after which submission is not accepted without an extension'),
520                 'teamsubmission' => new external_value(PARAM_INT, 'if enabled, students submit as a team'),
521                 'requireallteammemberssubmit' => new external_value(PARAM_INT, 'if enabled, all team members must submit'),
522                 'teamsubmissiongroupingid' => new external_value(PARAM_INT, 'the grouping id for the team submission groups'),
523                 'blindmarking' => new external_value(PARAM_INT, 'if enabled, hide identities until reveal identities actioned'),
524                 'revealidentities' => new external_value(PARAM_INT, 'show identities for a blind marking assignment'),
525                 'attemptreopenmethod' => new external_value(PARAM_TEXT, 'method used to control opening new attempts'),
526                 'maxattempts' => new external_value(PARAM_INT, 'maximum number of attempts allowed'),
527                 'markingworkflow' => new external_value(PARAM_INT, 'enable marking workflow'),
528                 'markingallocation' => new external_value(PARAM_INT, 'enable marking allocation'),
529                 'requiresubmissionstatement' => new external_value(PARAM_INT, 'student must accept submission statement'),
530                 'preventsubmissionnotingroup' => new external_value(PARAM_INT, 'Prevent submission not in group', VALUE_OPTIONAL),
531                 'submissionstatement' => new external_value(PARAM_RAW, 'Submission statement formatted.', VALUE_OPTIONAL),
532                 'submissionstatementformat' => new external_format_value('submissionstatement', VALUE_OPTIONAL),
533                 'configs' => new external_multiple_structure(self::get_assignments_config_structure(), 'configuration settings'),
534                 'intro' => new external_value(PARAM_RAW,
535                     'assignment intro, not allways returned because it deppends on the activity configuration', VALUE_OPTIONAL),
536                 'introformat' => new external_format_value('intro', VALUE_OPTIONAL),
537                 'introfiles' => new external_files('Files in the introduction text', VALUE_OPTIONAL),
538                 'introattachments' => new external_files('intro attachments files', VALUE_OPTIONAL),
539             ), 'assignment information object');
540     }
542     /**
543      * Creates an assign_plugin_config external_single_structure
544      *
545      * @return external_single_structure
546      * @since Moodle 2.4
547      */
548     private static function get_assignments_config_structure() {
549         return new external_single_structure(
550             array(
551                 'id' => new external_value(PARAM_INT, 'assign_plugin_config id', VALUE_OPTIONAL),
552                 'assignment' => new external_value(PARAM_INT, 'assignment id', VALUE_OPTIONAL),
553                 'plugin' => new external_value(PARAM_TEXT, 'plugin'),
554                 'subtype' => new external_value(PARAM_TEXT, 'subtype'),
555                 'name' => new external_value(PARAM_TEXT, 'name'),
556                 'value' => new external_value(PARAM_TEXT, 'value')
557             ), 'assignment configuration object'
558         );
559     }
561     /**
562      * Creates a course external_single_structure
563      *
564      * @return external_single_structure
565      * @since Moodle 2.4
566      */
567     private static function get_assignments_course_structure() {
568         return new external_single_structure(
569             array(
570                 'id' => new external_value(PARAM_INT, 'course id'),
571                 'fullname' => new external_value(PARAM_TEXT, 'course full name'),
572                 'shortname' => new external_value(PARAM_TEXT, 'course short name'),
573                 'timemodified' => new external_value(PARAM_INT, 'last time modified'),
574                 'assignments' => new external_multiple_structure(self::get_assignments_assignment_structure(), 'assignment info')
575               ), 'course information object'
576         );
577     }
579     /**
580      * Describes the return value for get_assignments
581      *
582      * @return external_single_structure
583      * @since Moodle 2.4
584      */
585     public static function get_assignments_returns() {
586         return new external_single_structure(
587             array(
588                 'courses' => new external_multiple_structure(self::get_assignments_course_structure(), 'list of courses'),
589                 'warnings'  => new external_warnings('item can be \'course\' (errorcode 1 or 2) or \'module\' (errorcode 1)',
590                     'When item is a course then itemid is a course id. When the item is a module then itemid is a module id',
591                     'errorcode can be 1 (no access rights) or 2 (not enrolled or no permissions)')
592             )
593         );
594     }
596     /**
597      * Return information (files and text fields) for the given plugins in the assignment.
598      *
599      * @param  assign $assign the assignment object
600      * @param  array $assignplugins array of assignment plugins (submission or feedback)
601      * @param  stdClass $item the item object (submission or grade)
602      * @return array an array containing the plugins returned information
603      */
604     private static function get_plugins_data($assign, $assignplugins, $item) {
605         global $CFG;
607         $plugins = array();
608         $fs = get_file_storage();
610         foreach ($assignplugins as $assignplugin) {
612             if (!$assignplugin->is_enabled() or !$assignplugin->is_visible()) {
613                 continue;
614             }
616             $plugin = array(
617                 'name' => $assignplugin->get_name(),
618                 'type' => $assignplugin->get_type()
619             );
620             // Subtype is 'assignsubmission', type is currently 'file' or 'onlinetext'.
621             $component = $assignplugin->get_subtype().'_'.$assignplugin->get_type();
623             $fileareas = $assignplugin->get_file_areas();
624             foreach ($fileareas as $filearea => $name) {
625                 $fileareainfo = array('area' => $filearea);
627                 $fileareainfo['files'] = external_util::get_area_files(
628                     $assign->get_context()->id,
629                     $component,
630                     $filearea,
631                     $item->id
632                 );
634                 $plugin['fileareas'][] = $fileareainfo;
635             }
637             $editorfields = $assignplugin->get_editor_fields();
638             foreach ($editorfields as $name => $description) {
639                 $editorfieldinfo = array(
640                     'name' => $name,
641                     'description' => $description,
642                     'text' => $assignplugin->get_editor_text($name, $item->id),
643                     'format' => $assignplugin->get_editor_format($name, $item->id)
644                 );
646                 // Now format the text.
647                 foreach ($fileareas as $filearea => $name) {
648                     list($editorfieldinfo['text'], $editorfieldinfo['format']) = external_format_text(
649                         $editorfieldinfo['text'], $editorfieldinfo['format'], $assign->get_context()->id,
650                         $component, $filearea, $item->id);
651                 }
653                 $plugin['editorfields'][] = $editorfieldinfo;
654             }
655             $plugins[] = $plugin;
656         }
657         return $plugins;
658     }
660     /**
661      * Describes the parameters for get_submissions
662      *
663      * @return external_external_function_parameters
664      * @since Moodle 2.5
665      */
666     public static function get_submissions_parameters() {
667         return new external_function_parameters(
668             array(
669                 'assignmentids' => new external_multiple_structure(
670                     new external_value(PARAM_INT, 'assignment id'),
671                     '1 or more assignment ids',
672                     VALUE_REQUIRED),
673                 'status' => new external_value(PARAM_ALPHA, 'status', VALUE_DEFAULT, ''),
674                 'since' => new external_value(PARAM_INT, 'submitted since', VALUE_DEFAULT, 0),
675                 'before' => new external_value(PARAM_INT, 'submitted before', VALUE_DEFAULT, 0)
676             )
677         );
678     }
680     /**
681      * Returns submissions for the requested assignment ids
682      *
683      * @param int[] $assignmentids
684      * @param string $status only return submissions with this status
685      * @param int $since only return submissions with timemodified >= since
686      * @param int $before only return submissions with timemodified <= before
687      * @return array of submissions for each requested assignment
688      * @since Moodle 2.5
689      */
690     public static function get_submissions($assignmentids, $status = '', $since = 0, $before = 0) {
691         global $DB, $CFG;
693         $params = self::validate_parameters(self::get_submissions_parameters(),
694                         array('assignmentids' => $assignmentids,
695                               'status' => $status,
696                               'since' => $since,
697                               'before' => $before));
699         $warnings = array();
700         $assignments = array();
702         // Check the user is allowed to get the submissions for the assignments requested.
703         $placeholders = array();
704         list($inorequalsql, $placeholders) = $DB->get_in_or_equal($params['assignmentids'], SQL_PARAMS_NAMED);
705         $sql = "SELECT cm.id, cm.instance FROM {course_modules} cm JOIN {modules} md ON md.id = cm.module ".
706                "WHERE md.name = :modname AND cm.instance ".$inorequalsql;
707         $placeholders['modname'] = 'assign';
708         $cms = $DB->get_records_sql($sql, $placeholders);
709         $assigns = array();
710         foreach ($cms as $cm) {
711             try {
712                 $context = context_module::instance($cm->id);
713                 self::validate_context($context);
714                 require_capability('mod/assign:grade', $context);
715                 $assign = new assign($context, null, null);
716                 $assigns[] = $assign;
717             } catch (Exception $e) {
718                 $warnings[] = array(
719                     'item' => 'assignment',
720                     'itemid' => $cm->instance,
721                     'warningcode' => '1',
722                     'message' => 'No access rights in module context'
723                 );
724             }
725         }
727         foreach ($assigns as $assign) {
728             $submissions = array();
729             $placeholders = array('assignid1' => $assign->get_instance()->id,
730                                   'assignid2' => $assign->get_instance()->id);
732             $submissionmaxattempt = 'SELECT mxs.userid, MAX(mxs.attemptnumber) AS maxattempt
733                                      FROM {assign_submission} mxs
734                                      WHERE mxs.assignment = :assignid1 GROUP BY mxs.userid';
736             $sql = "SELECT mas.id, mas.assignment,mas.userid,".
737                    "mas.timecreated,mas.timemodified,mas.status,mas.groupid,mas.attemptnumber ".
738                    "FROM {assign_submission} mas ".
739                    "JOIN ( " . $submissionmaxattempt . " ) smx ON mas.userid = smx.userid ".
740                    "WHERE mas.assignment = :assignid2 AND mas.attemptnumber = smx.maxattempt";
742             if (!empty($params['status'])) {
743                 $placeholders['status'] = $params['status'];
744                 $sql = $sql." AND mas.status = :status";
745             }
746             if (!empty($params['before'])) {
747                 $placeholders['since'] = $params['since'];
748                 $placeholders['before'] = $params['before'];
749                 $sql = $sql." AND mas.timemodified BETWEEN :since AND :before";
750             } else {
751                 $placeholders['since'] = $params['since'];
752                 $sql = $sql." AND mas.timemodified >= :since";
753             }
755             $submissionrecords = $DB->get_records_sql($sql, $placeholders);
757             if (!empty($submissionrecords)) {
758                 $submissionplugins = $assign->get_submission_plugins();
759                 foreach ($submissionrecords as $submissionrecord) {
760                     $submission = array(
761                         'id' => $submissionrecord->id,
762                         'userid' => $submissionrecord->userid,
763                         'timecreated' => $submissionrecord->timecreated,
764                         'timemodified' => $submissionrecord->timemodified,
765                         'status' => $submissionrecord->status,
766                         'attemptnumber' => $submissionrecord->attemptnumber,
767                         'groupid' => $submissionrecord->groupid,
768                         'plugins' => self::get_plugins_data($assign, $submissionplugins, $submissionrecord),
769                         'gradingstatus' => $assign->get_grading_status($submissionrecord->userid)
770                     );
771                     $submissions[] = $submission;
772                 }
773             } else {
774                 $warnings[] = array(
775                     'item' => 'module',
776                     'itemid' => $assign->get_instance()->id,
777                     'warningcode' => '3',
778                     'message' => 'No submissions found'
779                 );
780             }
782             $assignments[] = array(
783                 'assignmentid' => $assign->get_instance()->id,
784                 'submissions' => $submissions
785             );
787         }
789         $result = array(
790             'assignments' => $assignments,
791             'warnings' => $warnings
792         );
793         return $result;
794     }
796     /**
797      * Creates an assignment plugin structure.
798      *
799      * @return external_single_structure the plugin structure
800      */
801     private static function get_plugin_structure() {
802         return new external_single_structure(
803             array(
804                 'type' => new external_value(PARAM_TEXT, 'submission plugin type'),
805                 'name' => new external_value(PARAM_TEXT, 'submission plugin name'),
806                 'fileareas' => new external_multiple_structure(
807                     new external_single_structure(
808                         array (
809                             'area' => new external_value (PARAM_TEXT, 'file area'),
810                             'files' => new external_files('files', VALUE_OPTIONAL),
811                         )
812                     ), 'fileareas', VALUE_OPTIONAL
813                 ),
814                 'editorfields' => new external_multiple_structure(
815                     new external_single_structure(
816                         array(
817                             'name' => new external_value(PARAM_TEXT, 'field name'),
818                             'description' => new external_value(PARAM_TEXT, 'field description'),
819                             'text' => new external_value (PARAM_RAW, 'field value'),
820                             'format' => new external_format_value ('text')
821                         )
822                     )
823                     , 'editorfields', VALUE_OPTIONAL
824                 )
825             )
826         );
827     }
829     /**
830      * Creates a submission structure.
831      *
832      * @return external_single_structure the submission structure
833      */
834     private static function get_submission_structure($required = VALUE_REQUIRED) {
835         return new external_single_structure(
836             array(
837                 'id' => new external_value(PARAM_INT, 'submission id'),
838                 'userid' => new external_value(PARAM_INT, 'student id'),
839                 'attemptnumber' => new external_value(PARAM_INT, 'attempt number'),
840                 'timecreated' => new external_value(PARAM_INT, 'submission creation time'),
841                 'timemodified' => new external_value(PARAM_INT, 'submission last modified time'),
842                 'status' => new external_value(PARAM_TEXT, 'submission status'),
843                 'groupid' => new external_value(PARAM_INT, 'group id'),
844                 'assignment' => new external_value(PARAM_INT, 'assignment id', VALUE_OPTIONAL),
845                 'latest' => new external_value(PARAM_INT, 'latest attempt', VALUE_OPTIONAL),
846                 'plugins' => new external_multiple_structure(self::get_plugin_structure(), 'plugins', VALUE_OPTIONAL),
847                 'gradingstatus' => new external_value(PARAM_ALPHANUMEXT, 'Grading status.', VALUE_OPTIONAL),
848             ), 'submission info', $required
849         );
850     }
852     /**
853      * Creates an assign_submissions external_single_structure
854      *
855      * @return external_single_structure
856      * @since Moodle 2.5
857      */
858     private static function get_submissions_structure() {
859         return new external_single_structure(
860             array (
861                 'assignmentid' => new external_value(PARAM_INT, 'assignment id'),
862                 'submissions' => new external_multiple_structure(self::get_submission_structure())
863             )
864         );
865     }
867     /**
868      * Describes the get_submissions return value
869      *
870      * @return external_single_structure
871      * @since Moodle 2.5
872      */
873     public static function get_submissions_returns() {
874         return new external_single_structure(
875             array(
876                 'assignments' => new external_multiple_structure(self::get_submissions_structure(), 'assignment submissions'),
877                 'warnings' => new external_warnings()
878             )
879         );
880     }
882     /**
883      * Describes the parameters for set_user_flags
884      * @return external_function_parameters
885      * @since  Moodle 2.6
886      */
887     public static function set_user_flags_parameters() {
888         return new external_function_parameters(
889             array(
890                 'assignmentid'    => new external_value(PARAM_INT, 'assignment id'),
891                 'userflags' => new external_multiple_structure(
892                     new external_single_structure(
893                         array(
894                             'userid'           => new external_value(PARAM_INT, 'student id'),
895                             'locked'           => new external_value(PARAM_INT, 'locked', VALUE_OPTIONAL),
896                             'mailed'           => new external_value(PARAM_INT, 'mailed', VALUE_OPTIONAL),
897                             'extensionduedate' => new external_value(PARAM_INT, 'extension due date', VALUE_OPTIONAL),
898                             'workflowstate'    => new external_value(PARAM_ALPHA, 'marking workflow state', VALUE_OPTIONAL),
899                             'allocatedmarker'  => new external_value(PARAM_INT, 'allocated marker', VALUE_OPTIONAL)
900                         )
901                     )
902                 )
903             )
904         );
905     }
907     /**
908      * Create or update user_flags records
909      *
910      * @param int $assignmentid the assignment for which the userflags are created or updated
911      * @param array $userflags  An array of userflags to create or update
912      * @return array containing success or failure information for each record
913      * @since Moodle 2.6
914      */
915     public static function set_user_flags($assignmentid, $userflags = array()) {
916         global $CFG, $DB;
918         $params = self::validate_parameters(self::set_user_flags_parameters(),
919                                             array('assignmentid' => $assignmentid,
920                                                   'userflags' => $userflags));
922         // Load assignment if it exists and if the user has the capability.
923         list($assign, $course, $cm, $context) = self::validate_assign($params['assignmentid']);
924         require_capability('mod/assign:grade', $context);
926         $results = array();
927         foreach ($params['userflags'] as $userflag) {
928             $success = true;
929             $result = array();
931             $record = $assign->get_user_flags($userflag['userid'], false);
932             if ($record) {
933                 if (isset($userflag['locked'])) {
934                     $record->locked = $userflag['locked'];
935                 }
936                 if (isset($userflag['mailed'])) {
937                     $record->mailed = $userflag['mailed'];
938                 }
939                 if (isset($userflag['extensionduedate'])) {
940                     $record->extensionduedate = $userflag['extensionduedate'];
941                 }
942                 if (isset($userflag['workflowstate'])) {
943                     $record->workflowstate = $userflag['workflowstate'];
944                 }
945                 if (isset($userflag['allocatedmarker'])) {
946                     $record->allocatedmarker = $userflag['allocatedmarker'];
947                 }
948                 if ($assign->update_user_flags($record)) {
949                     $result['id'] = $record->id;
950                     $result['userid'] = $userflag['userid'];
951                 } else {
952                     $result['id'] = $record->id;
953                     $result['userid'] = $userflag['userid'];
954                     $result['errormessage'] = 'Record created but values could not be set';
955                 }
956             } else {
957                 $record = $assign->get_user_flags($userflag['userid'], true);
958                 $setfields = isset($userflag['locked'])
959                              || isset($userflag['mailed'])
960                              || isset($userflag['extensionduedate'])
961                              || isset($userflag['workflowstate'])
962                              || isset($userflag['allocatedmarker']);
963                 if ($record) {
964                     if ($setfields) {
965                         if (isset($userflag['locked'])) {
966                             $record->locked = $userflag['locked'];
967                         }
968                         if (isset($userflag['mailed'])) {
969                             $record->mailed = $userflag['mailed'];
970                         }
971                         if (isset($userflag['extensionduedate'])) {
972                             $record->extensionduedate = $userflag['extensionduedate'];
973                         }
974                         if (isset($userflag['workflowstate'])) {
975                             $record->workflowstate = $userflag['workflowstate'];
976                         }
977                         if (isset($userflag['allocatedmarker'])) {
978                             $record->allocatedmarker = $userflag['allocatedmarker'];
979                         }
980                         if ($assign->update_user_flags($record)) {
981                             $result['id'] = $record->id;
982                             $result['userid'] = $userflag['userid'];
983                         } else {
984                             $result['id'] = $record->id;
985                             $result['userid'] = $userflag['userid'];
986                             $result['errormessage'] = 'Record created but values could not be set';
987                         }
988                     } else {
989                         $result['id'] = $record->id;
990                         $result['userid'] = $userflag['userid'];
991                     }
992                 } else {
993                     $result['id'] = -1;
994                     $result['userid'] = $userflag['userid'];
995                     $result['errormessage'] = 'Record could not be created';
996                 }
997             }
999             $results[] = $result;
1000         }
1001         return $results;
1002     }
1004     /**
1005      * Describes the set_user_flags return value
1006      * @return external_multiple_structure
1007      * @since  Moodle 2.6
1008      */
1009     public static function set_user_flags_returns() {
1010         return new external_multiple_structure(
1011             new external_single_structure(
1012                 array(
1013                     'id' => new external_value(PARAM_INT, 'id of record if successful, -1 for failure'),
1014                     'userid' => new external_value(PARAM_INT, 'userid of record'),
1015                     'errormessage' => new external_value(PARAM_TEXT, 'Failure error message', VALUE_OPTIONAL)
1016                 )
1017             )
1018         );
1019     }
1021     /**
1022      * Describes the parameters for get_user_flags
1023      * @return external_function_parameters
1024      * @since  Moodle 2.6
1025      */
1026     public static function get_user_flags_parameters() {
1027         return new external_function_parameters(
1028             array(
1029                 'assignmentids' => new external_multiple_structure(
1030                     new external_value(PARAM_INT, 'assignment id'),
1031                     '1 or more assignment ids',
1032                     VALUE_REQUIRED)
1033             )
1034         );
1035     }
1037     /**
1038      * Returns user flag information from assign_user_flags for the requested assignment ids
1039      * @param int[] $assignmentids
1040      * @return array of user flag records for each requested assignment
1041      * @since  Moodle 2.6
1042      */
1043     public static function get_user_flags($assignmentids) {
1044         global $DB;
1045         $params = self::validate_parameters(self::get_user_flags_parameters(),
1046                         array('assignmentids' => $assignmentids));
1048         $assignments = array();
1049         $warnings = array();
1050         $requestedassignmentids = $params['assignmentids'];
1052         // Check the user is allowed to get the user flags for the assignments requested.
1053         $placeholders = array();
1054         list($sqlassignmentids, $placeholders) = $DB->get_in_or_equal($requestedassignmentids, SQL_PARAMS_NAMED);
1055         $sql = "SELECT cm.id, cm.instance FROM {course_modules} cm JOIN {modules} md ON md.id = cm.module ".
1056                "WHERE md.name = :modname AND cm.instance ".$sqlassignmentids;
1057         $placeholders['modname'] = 'assign';
1058         $cms = $DB->get_records_sql($sql, $placeholders);
1059         foreach ($cms as $cm) {
1060             try {
1061                 $context = context_module::instance($cm->id);
1062                 self::validate_context($context);
1063                 require_capability('mod/assign:grade', $context);
1064             } catch (Exception $e) {
1065                 $requestedassignmentids = array_diff($requestedassignmentids, array($cm->instance));
1066                 $warning = array();
1067                 $warning['item'] = 'assignment';
1068                 $warning['itemid'] = $cm->instance;
1069                 $warning['warningcode'] = '1';
1070                 $warning['message'] = 'No access rights in module context';
1071                 $warnings[] = $warning;
1072             }
1073         }
1075         // Create the query and populate an array of assign_user_flags records from the recordset results.
1076         if (count ($requestedassignmentids) > 0) {
1077             $placeholders = array();
1078             list($inorequalsql, $placeholders) = $DB->get_in_or_equal($requestedassignmentids, SQL_PARAMS_NAMED);
1080             $sql = "SELECT auf.id,auf.assignment,auf.userid,auf.locked,auf.mailed,".
1081                    "auf.extensionduedate,auf.workflowstate,auf.allocatedmarker ".
1082                    "FROM {assign_user_flags} auf ".
1083                    "WHERE auf.assignment ".$inorequalsql.
1084                    " ORDER BY auf.assignment, auf.id";
1086             $rs = $DB->get_recordset_sql($sql, $placeholders);
1087             $currentassignmentid = null;
1088             $assignment = null;
1089             foreach ($rs as $rd) {
1090                 $userflag = array();
1091                 $userflag['id'] = $rd->id;
1092                 $userflag['userid'] = $rd->userid;
1093                 $userflag['locked'] = $rd->locked;
1094                 $userflag['mailed'] = $rd->mailed;
1095                 $userflag['extensionduedate'] = $rd->extensionduedate;
1096                 $userflag['workflowstate'] = $rd->workflowstate;
1097                 $userflag['allocatedmarker'] = $rd->allocatedmarker;
1099                 if (is_null($currentassignmentid) || ($rd->assignment != $currentassignmentid )) {
1100                     if (!is_null($assignment)) {
1101                         $assignments[] = $assignment;
1102                     }
1103                     $assignment = array();
1104                     $assignment['assignmentid'] = $rd->assignment;
1105                     $assignment['userflags'] = array();
1106                     $requestedassignmentids = array_diff($requestedassignmentids, array($rd->assignment));
1107                 }
1108                 $assignment['userflags'][] = $userflag;
1110                 $currentassignmentid = $rd->assignment;
1111             }
1112             if (!is_null($assignment)) {
1113                 $assignments[] = $assignment;
1114             }
1115             $rs->close();
1117         }
1119         foreach ($requestedassignmentids as $assignmentid) {
1120             $warning = array();
1121             $warning['item'] = 'assignment';
1122             $warning['itemid'] = $assignmentid;
1123             $warning['warningcode'] = '3';
1124             $warning['message'] = 'No user flags found';
1125             $warnings[] = $warning;
1126         }
1128         $result = array();
1129         $result['assignments'] = $assignments;
1130         $result['warnings'] = $warnings;
1131         return $result;
1132     }
1134     /**
1135      * Creates an assign_user_flags external_single_structure
1136      * @return external_single_structure
1137      * @since  Moodle 2.6
1138      */
1139     private static function assign_user_flags() {
1140         return new external_single_structure(
1141             array (
1142                 'assignmentid'    => new external_value(PARAM_INT, 'assignment id'),
1143                 'userflags'   => new external_multiple_structure(new external_single_structure(
1144                         array(
1145                             'id'               => new external_value(PARAM_INT, 'user flag id'),
1146                             'userid'           => new external_value(PARAM_INT, 'student id'),
1147                             'locked'           => new external_value(PARAM_INT, 'locked'),
1148                             'mailed'           => new external_value(PARAM_INT, 'mailed'),
1149                             'extensionduedate' => new external_value(PARAM_INT, 'extension due date'),
1150                             'workflowstate'    => new external_value(PARAM_ALPHA, 'marking workflow state', VALUE_OPTIONAL),
1151                             'allocatedmarker'  => new external_value(PARAM_INT, 'allocated marker')
1152                         )
1153                     )
1154                 )
1155             )
1156         );
1157     }
1159     /**
1160      * Describes the get_user_flags return value
1161      * @return external_single_structure
1162      * @since  Moodle 2.6
1163      */
1164     public static function get_user_flags_returns() {
1165         return new external_single_structure(
1166             array(
1167                 'assignments' => new external_multiple_structure(self::assign_user_flags(), 'list of assign user flag information'),
1168                 'warnings'      => new external_warnings('item is always \'assignment\'',
1169                     'when errorcode is 3 then itemid is an assignment id. When errorcode is 1, itemid is a course module id',
1170                     'errorcode can be 3 (no user flags found) or 1 (no permission to get user flags)')
1171             )
1172         );
1173     }
1175     /**
1176      * Describes the parameters for get_user_mappings
1177      * @return external_function_parameters
1178      * @since  Moodle 2.6
1179      */
1180     public static function get_user_mappings_parameters() {
1181         return new external_function_parameters(
1182             array(
1183                 'assignmentids' => new external_multiple_structure(
1184                     new external_value(PARAM_INT, 'assignment id'),
1185                     '1 or more assignment ids',
1186                     VALUE_REQUIRED)
1187             )
1188         );
1189     }
1191     /**
1192      * Returns user mapping information from assign_user_mapping for the requested assignment ids
1193      * @param int[] $assignmentids
1194      * @return array of user mapping records for each requested assignment
1195      * @since  Moodle 2.6
1196      */
1197     public static function get_user_mappings($assignmentids) {
1198         global $DB;
1199         $params = self::validate_parameters(self::get_user_mappings_parameters(),
1200                         array('assignmentids' => $assignmentids));
1202         $assignments = array();
1203         $warnings = array();
1204         $requestedassignmentids = $params['assignmentids'];
1206         // Check the user is allowed to get the mappings for the assignments requested.
1207         $placeholders = array();
1208         list($sqlassignmentids, $placeholders) = $DB->get_in_or_equal($requestedassignmentids, SQL_PARAMS_NAMED);
1209         $sql = "SELECT cm.id, cm.instance FROM {course_modules} cm JOIN {modules} md ON md.id = cm.module ".
1210                "WHERE md.name = :modname AND cm.instance ".$sqlassignmentids;
1211         $placeholders['modname'] = 'assign';
1212         $cms = $DB->get_records_sql($sql, $placeholders);
1213         foreach ($cms as $cm) {
1214             try {
1215                 $context = context_module::instance($cm->id);
1216                 self::validate_context($context);
1217                 require_capability('mod/assign:revealidentities', $context);
1218             } catch (Exception $e) {
1219                 $requestedassignmentids = array_diff($requestedassignmentids, array($cm->instance));
1220                 $warning = array();
1221                 $warning['item'] = 'assignment';
1222                 $warning['itemid'] = $cm->instance;
1223                 $warning['warningcode'] = '1';
1224                 $warning['message'] = 'No access rights in module context';
1225                 $warnings[] = $warning;
1226             }
1227         }
1229         // Create the query and populate an array of assign_user_mapping records from the recordset results.
1230         if (count ($requestedassignmentids) > 0) {
1231             $placeholders = array();
1232             list($inorequalsql, $placeholders) = $DB->get_in_or_equal($requestedassignmentids, SQL_PARAMS_NAMED);
1234             $sql = "SELECT aum.id,aum.assignment,aum.userid ".
1235                    "FROM {assign_user_mapping} aum ".
1236                    "WHERE aum.assignment ".$inorequalsql.
1237                    " ORDER BY aum.assignment, aum.id";
1239             $rs = $DB->get_recordset_sql($sql, $placeholders);
1240             $currentassignmentid = null;
1241             $assignment = null;
1242             foreach ($rs as $rd) {
1243                 $mapping = array();
1244                 $mapping['id'] = $rd->id;
1245                 $mapping['userid'] = $rd->userid;
1247                 if (is_null($currentassignmentid) || ($rd->assignment != $currentassignmentid )) {
1248                     if (!is_null($assignment)) {
1249                         $assignments[] = $assignment;
1250                     }
1251                     $assignment = array();
1252                     $assignment['assignmentid'] = $rd->assignment;
1253                     $assignment['mappings'] = array();
1254                     $requestedassignmentids = array_diff($requestedassignmentids, array($rd->assignment));
1255                 }
1256                 $assignment['mappings'][] = $mapping;
1258                 $currentassignmentid = $rd->assignment;
1259             }
1260             if (!is_null($assignment)) {
1261                 $assignments[] = $assignment;
1262             }
1263             $rs->close();
1265         }
1267         foreach ($requestedassignmentids as $assignmentid) {
1268             $warning = array();
1269             $warning['item'] = 'assignment';
1270             $warning['itemid'] = $assignmentid;
1271             $warning['warningcode'] = '3';
1272             $warning['message'] = 'No mappings found';
1273             $warnings[] = $warning;
1274         }
1276         $result = array();
1277         $result['assignments'] = $assignments;
1278         $result['warnings'] = $warnings;
1279         return $result;
1280     }
1282     /**
1283      * Creates an assign_user_mappings external_single_structure
1284      * @return external_single_structure
1285      * @since  Moodle 2.6
1286      */
1287     private static function assign_user_mappings() {
1288         return new external_single_structure(
1289             array (
1290                 'assignmentid'    => new external_value(PARAM_INT, 'assignment id'),
1291                 'mappings'   => new external_multiple_structure(new external_single_structure(
1292                         array(
1293                             'id'     => new external_value(PARAM_INT, 'user mapping id'),
1294                             'userid' => new external_value(PARAM_INT, 'student id')
1295                         )
1296                     )
1297                 )
1298             )
1299         );
1300     }
1302     /**
1303      * Describes the get_user_mappings return value
1304      * @return external_single_structure
1305      * @since  Moodle 2.6
1306      */
1307     public static function get_user_mappings_returns() {
1308         return new external_single_structure(
1309             array(
1310                 'assignments' => new external_multiple_structure(self::assign_user_mappings(), 'list of assign user mapping data'),
1311                 'warnings'      => new external_warnings('item is always \'assignment\'',
1312                     'when errorcode is 3 then itemid is an assignment id. When errorcode is 1, itemid is a course module id',
1313                     'errorcode can be 3 (no user mappings found) or 1 (no permission to get user mappings)')
1314             )
1315         );
1316     }
1318     /**
1319      * Describes the parameters for lock_submissions
1320      * @return external_external_function_parameters
1321      * @since  Moodle 2.6
1322      */
1323     public static function lock_submissions_parameters() {
1324         return new external_function_parameters(
1325             array(
1326                 'assignmentid' => new external_value(PARAM_INT, 'The assignment id to operate on'),
1327                 'userids' => new external_multiple_structure(
1328                     new external_value(PARAM_INT, 'user id'),
1329                     '1 or more user ids',
1330                     VALUE_REQUIRED),
1331             )
1332         );
1333     }
1335     /**
1336      * Locks (prevent updates to) submissions in this assignment.
1337      *
1338      * @param int $assignmentid The id of the assignment
1339      * @param array $userids Array of user ids to lock
1340      * @return array of warnings for each submission that could not be locked.
1341      * @since Moodle 2.6
1342      */
1343     public static function lock_submissions($assignmentid, $userids) {
1344         global $CFG;
1346         $params = self::validate_parameters(self::lock_submissions_parameters(),
1347                         array('assignmentid' => $assignmentid,
1348                               'userids' => $userids));
1350         list($assignment, $course, $cm, $context) = self::validate_assign($params['assignmentid']);
1352         $warnings = array();
1353         foreach ($params['userids'] as $userid) {
1354             if (!$assignment->lock_submission($userid)) {
1355                 $detail = 'User id: ' . $userid . ', Assignment id: ' . $params['assignmentid'];
1356                 $warnings[] = self::generate_warning($params['assignmentid'],
1357                                                      'couldnotlock',
1358                                                      $detail);
1359             }
1360         }
1362         return $warnings;
1363     }
1365     /**
1366      * Describes the return value for lock_submissions
1367      *
1368      * @return external_single_structure
1369      * @since Moodle 2.6
1370      */
1371     public static function lock_submissions_returns() {
1372         return new external_warnings();
1373     }
1375     /**
1376      * Describes the parameters for revert_submissions_to_draft
1377      * @return external_external_function_parameters
1378      * @since  Moodle 2.6
1379      */
1380     public static function revert_submissions_to_draft_parameters() {
1381         return new external_function_parameters(
1382             array(
1383                 'assignmentid' => new external_value(PARAM_INT, 'The assignment id to operate on'),
1384                 'userids' => new external_multiple_structure(
1385                     new external_value(PARAM_INT, 'user id'),
1386                     '1 or more user ids',
1387                     VALUE_REQUIRED),
1388             )
1389         );
1390     }
1392     /**
1393      * Reverts a list of user submissions to draft for a single assignment.
1394      *
1395      * @param int $assignmentid The id of the assignment
1396      * @param array $userids Array of user ids to revert
1397      * @return array of warnings for each submission that could not be reverted.
1398      * @since Moodle 2.6
1399      */
1400     public static function revert_submissions_to_draft($assignmentid, $userids) {
1401         global $CFG;
1403         $params = self::validate_parameters(self::revert_submissions_to_draft_parameters(),
1404                         array('assignmentid' => $assignmentid,
1405                               'userids' => $userids));
1407         list($assignment, $course, $cm, $context) = self::validate_assign($params['assignmentid']);
1409         $warnings = array();
1410         foreach ($params['userids'] as $userid) {
1411             if (!$assignment->revert_to_draft($userid)) {
1412                 $detail = 'User id: ' . $userid . ', Assignment id: ' . $params['assignmentid'];
1413                 $warnings[] = self::generate_warning($params['assignmentid'],
1414                                                      'couldnotrevert',
1415                                                      $detail);
1416             }
1417         }
1419         return $warnings;
1420     }
1422     /**
1423      * Describes the return value for revert_submissions_to_draft
1424      *
1425      * @return external_single_structure
1426      * @since Moodle 2.6
1427      */
1428     public static function revert_submissions_to_draft_returns() {
1429         return new external_warnings();
1430     }
1432     /**
1433      * Describes the parameters for unlock_submissions
1434      * @return external_external_function_parameters
1435      * @since  Moodle 2.6
1436      */
1437     public static function unlock_submissions_parameters() {
1438         return new external_function_parameters(
1439             array(
1440                 'assignmentid' => new external_value(PARAM_INT, 'The assignment id to operate on'),
1441                 'userids' => new external_multiple_structure(
1442                     new external_value(PARAM_INT, 'user id'),
1443                     '1 or more user ids',
1444                     VALUE_REQUIRED),
1445             )
1446         );
1447     }
1449     /**
1450      * Locks (prevent updates to) submissions in this assignment.
1451      *
1452      * @param int $assignmentid The id of the assignment
1453      * @param array $userids Array of user ids to lock
1454      * @return array of warnings for each submission that could not be locked.
1455      * @since Moodle 2.6
1456      */
1457     public static function unlock_submissions($assignmentid, $userids) {
1458         global $CFG;
1460         $params = self::validate_parameters(self::unlock_submissions_parameters(),
1461                         array('assignmentid' => $assignmentid,
1462                               'userids' => $userids));
1464         list($assignment, $course, $cm, $context) = self::validate_assign($params['assignmentid']);
1466         $warnings = array();
1467         foreach ($params['userids'] as $userid) {
1468             if (!$assignment->unlock_submission($userid)) {
1469                 $detail = 'User id: ' . $userid . ', Assignment id: ' . $params['assignmentid'];
1470                 $warnings[] = self::generate_warning($params['assignmentid'],
1471                                                      'couldnotunlock',
1472                                                      $detail);
1473             }
1474         }
1476         return $warnings;
1477     }
1479     /**
1480      * Describes the return value for unlock_submissions
1481      *
1482      * @return external_single_structure
1483      * @since Moodle 2.6
1484      */
1485     public static function unlock_submissions_returns() {
1486         return new external_warnings();
1487     }
1489     /**
1490      * Describes the parameters for submit_grading_form webservice.
1491      * @return external_external_function_parameters
1492      * @since  Moodle 3.1
1493      */
1494     public static function submit_grading_form_parameters() {
1495         return new external_function_parameters(
1496             array(
1497                 'assignmentid' => new external_value(PARAM_INT, 'The assignment id to operate on'),
1498                 'userid' => new external_value(PARAM_INT, 'The user id the submission belongs to'),
1499                 'jsonformdata' => new external_value(PARAM_RAW, 'The data from the grading form, encoded as a json array')
1500             )
1501         );
1502     }
1504     /**
1505      * Submit the logged in users assignment for grading.
1506      *
1507      * @param int $assignmentid The id of the assignment
1508      * @param int $userid The id of the user the submission belongs to.
1509      * @param string $jsonformdata The data from the form, encoded as a json array.
1510      * @return array of warnings to indicate any errors.
1511      * @since Moodle 3.1
1512      */
1513     public static function submit_grading_form($assignmentid, $userid, $jsonformdata) {
1514         global $CFG, $USER;
1516         require_once($CFG->dirroot . '/mod/assign/locallib.php');
1517         require_once($CFG->dirroot . '/mod/assign/gradeform.php');
1519         $params = self::validate_parameters(self::submit_grading_form_parameters(),
1520                                             array(
1521                                                 'assignmentid' => $assignmentid,
1522                                                 'userid' => $userid,
1523                                                 'jsonformdata' => $jsonformdata
1524                                             ));
1526         list($assignment, $course, $cm, $context) = self::validate_assign($params['assignmentid']);
1528         $serialiseddata = json_decode($params['jsonformdata']);
1530         $data = array();
1531         parse_str($serialiseddata, $data);
1533         $warnings = array();
1535         $options = array(
1536             'userid' => $params['userid'],
1537             'attemptnumber' => $data['attemptnumber'],
1538             'rownum' => 0,
1539             'gradingpanel' => true
1540         );
1542         if (WS_SERVER) {
1543             // Assume form submission if coming from WS.
1544             $USER->ignoresesskey = true;
1545             $data['_qf__mod_assign_grade_form_'.$params['userid']] = 1;
1546         }
1548         $customdata = (object) $data;
1549         $formparams = array($assignment, $customdata, $options);
1551         // Data is injected into the form by the last param for the constructor.
1552         $mform = new mod_assign_grade_form(null, $formparams, 'post', '', null, true, $data);
1553         $validateddata = $mform->get_data();
1555         if ($validateddata) {
1556             $assignment->save_grade($params['userid'], $validateddata);
1557         } else {
1558             $warnings[] = self::generate_warning($params['assignmentid'],
1559                                                  'couldnotsavegrade',
1560                                                  'Form validation failed.');
1561         }
1564         return $warnings;
1565     }
1567     /**
1568      * Describes the return for submit_grading_form
1569      * @return external_external_function_parameters
1570      * @since  Moodle 3.1
1571      */
1572     public static function submit_grading_form_returns() {
1573         return new external_warnings();
1574     }
1576     /**
1577      * Describes the parameters for submit_for_grading
1578      * @return external_external_function_parameters
1579      * @since  Moodle 2.6
1580      */
1581     public static function submit_for_grading_parameters() {
1582         return new external_function_parameters(
1583             array(
1584                 'assignmentid' => new external_value(PARAM_INT, 'The assignment id to operate on'),
1585                 'acceptsubmissionstatement' => new external_value(PARAM_BOOL, 'Accept the assignment submission statement')
1586             )
1587         );
1588     }
1590     /**
1591      * Submit the logged in users assignment for grading.
1592      *
1593      * @param int $assignmentid The id of the assignment
1594      * @return array of warnings to indicate any errors.
1595      * @since Moodle 2.6
1596      */
1597     public static function submit_for_grading($assignmentid, $acceptsubmissionstatement) {
1598         global $CFG, $USER;
1600         $params = self::validate_parameters(self::submit_for_grading_parameters(),
1601                                             array('assignmentid' => $assignmentid,
1602                                                   'acceptsubmissionstatement' => $acceptsubmissionstatement));
1604         list($assignment, $course, $cm, $context) = self::validate_assign($params['assignmentid']);
1606         $warnings = array();
1607         $data = new stdClass();
1608         $data->submissionstatement = $params['acceptsubmissionstatement'];
1609         $notices = array();
1611         if (!$assignment->submit_for_grading($data, $notices)) {
1612             $detail = 'User id: ' . $USER->id . ', Assignment id: ' . $params['assignmentid'] . ' Notices:' . implode(', ', $notices);
1613             $warnings[] = self::generate_warning($params['assignmentid'],
1614                                                  'couldnotsubmitforgrading',
1615                                                  $detail);
1616         }
1618         return $warnings;
1619     }
1621     /**
1622      * Describes the return value for submit_for_grading
1623      *
1624      * @return external_single_structure
1625      * @since Moodle 2.6
1626      */
1627     public static function submit_for_grading_returns() {
1628         return new external_warnings();
1629     }
1631     /**
1632      * Describes the parameters for save_user_extensions
1633      * @return external_external_function_parameters
1634      * @since  Moodle 2.6
1635      */
1636     public static function save_user_extensions_parameters() {
1637         return new external_function_parameters(
1638             array(
1639                 'assignmentid' => new external_value(PARAM_INT, 'The assignment id to operate on'),
1640                 'userids' => new external_multiple_structure(
1641                     new external_value(PARAM_INT, 'user id'),
1642                     '1 or more user ids',
1643                     VALUE_REQUIRED),
1644                 'dates' => new external_multiple_structure(
1645                     new external_value(PARAM_INT, 'dates'),
1646                     '1 or more extension dates (timestamp)',
1647                     VALUE_REQUIRED),
1648             )
1649         );
1650     }
1652     /**
1653      * Grant extension dates to students for an assignment.
1654      *
1655      * @param int $assignmentid The id of the assignment
1656      * @param array $userids Array of user ids to grant extensions to
1657      * @param array $dates Array of extension dates
1658      * @return array of warnings for each extension date that could not be granted
1659      * @since Moodle 2.6
1660      */
1661     public static function save_user_extensions($assignmentid, $userids, $dates) {
1662         global $CFG;
1664         $params = self::validate_parameters(self::save_user_extensions_parameters(),
1665                         array('assignmentid' => $assignmentid,
1666                               'userids' => $userids,
1667                               'dates' => $dates));
1669         if (count($params['userids']) != count($params['dates'])) {
1670             $detail = 'Length of userids and dates parameters differ.';
1671             $warnings[] = self::generate_warning($params['assignmentid'],
1672                                                  'invalidparameters',
1673                                                  $detail);
1675             return $warnings;
1676         }
1678         list($assignment, $course, $cm, $context) = self::validate_assign($params['assignmentid']);
1680         $warnings = array();
1681         foreach ($params['userids'] as $idx => $userid) {
1682             $duedate = $params['dates'][$idx];
1683             if (!$assignment->save_user_extension($userid, $duedate)) {
1684                 $detail = 'User id: ' . $userid . ', Assignment id: ' . $params['assignmentid'] . ', Extension date: ' . $duedate;
1685                 $warnings[] = self::generate_warning($params['assignmentid'],
1686                                                      'couldnotgrantextensions',
1687                                                      $detail);
1688             }
1689         }
1691         return $warnings;
1692     }
1694     /**
1695      * Describes the return value for save_user_extensions
1696      *
1697      * @return external_single_structure
1698      * @since Moodle 2.6
1699      */
1700     public static function save_user_extensions_returns() {
1701         return new external_warnings();
1702     }
1704     /**
1705      * Describes the parameters for reveal_identities
1706      * @return external_external_function_parameters
1707      * @since  Moodle 2.6
1708      */
1709     public static function reveal_identities_parameters() {
1710         return new external_function_parameters(
1711             array(
1712                 'assignmentid' => new external_value(PARAM_INT, 'The assignment id to operate on')
1713             )
1714         );
1715     }
1717     /**
1718      * Reveal the identities of anonymous students to markers for a single assignment.
1719      *
1720      * @param int $assignmentid The id of the assignment
1721      * @return array of warnings to indicate any errors.
1722      * @since Moodle 2.6
1723      */
1724     public static function reveal_identities($assignmentid) {
1725         global $CFG, $USER;
1727         $params = self::validate_parameters(self::reveal_identities_parameters(),
1728                                             array('assignmentid' => $assignmentid));
1730         list($assignment, $course, $cm, $context) = self::validate_assign($params['assignmentid']);
1732         $warnings = array();
1733         if (!$assignment->reveal_identities()) {
1734             $detail = 'User id: ' . $USER->id . ', Assignment id: ' . $params['assignmentid'];
1735             $warnings[] = self::generate_warning($params['assignmentid'],
1736                                                  'couldnotrevealidentities',
1737                                                  $detail);
1738         }
1740         return $warnings;
1741     }
1743     /**
1744      * Describes the return value for reveal_identities
1745      *
1746      * @return external_single_structure
1747      * @since Moodle 2.6
1748      */
1749     public static function reveal_identities_returns() {
1750         return new external_warnings();
1751     }
1753     /**
1754      * Describes the parameters for save_submission
1755      * @return external_external_function_parameters
1756      * @since  Moodle 2.6
1757      */
1758     public static function save_submission_parameters() {
1759         global $CFG;
1760         $instance = new assign(null, null, null);
1761         $pluginsubmissionparams = array();
1763         foreach ($instance->get_submission_plugins() as $plugin) {
1764             if ($plugin->is_visible()) {
1765                 $pluginparams = $plugin->get_external_parameters();
1766                 if (!empty($pluginparams)) {
1767                     $pluginsubmissionparams = array_merge($pluginsubmissionparams, $pluginparams);
1768                 }
1769             }
1770         }
1772         return new external_function_parameters(
1773             array(
1774                 'assignmentid' => new external_value(PARAM_INT, 'The assignment id to operate on'),
1775                 'plugindata' => new external_single_structure(
1776                     $pluginsubmissionparams
1777                 )
1778             )
1779         );
1780     }
1782     /**
1783      * Save a student submission for a single assignment
1784      *
1785      * @param int $assignmentid The id of the assignment
1786      * @param array $plugindata - The submitted data for plugins
1787      * @return array of warnings to indicate any errors
1788      * @since Moodle 2.6
1789      */
1790     public static function save_submission($assignmentid, $plugindata) {
1791         global $CFG, $USER;
1793         $params = self::validate_parameters(self::save_submission_parameters(),
1794                                             array('assignmentid' => $assignmentid,
1795                                                   'plugindata' => $plugindata));
1797         list($assignment, $course, $cm, $context) = self::validate_assign($params['assignmentid']);
1799         $notices = array();
1801         $assignment->update_effective_access($USER->id);
1802         if (!$assignment->submissions_open($USER->id)) {
1803             $notices[] = get_string('duedatereached', 'assign');
1804         } else {
1805             $submissiondata = (object)$params['plugindata'];
1806             $assignment->save_submission($submissiondata, $notices);
1807         }
1809         $warnings = array();
1810         foreach ($notices as $notice) {
1811             $warnings[] = self::generate_warning($params['assignmentid'],
1812                                                  'couldnotsavesubmission',
1813                                                  $notice);
1814         }
1816         return $warnings;
1817     }
1819     /**
1820      * Describes the return value for save_submission
1821      *
1822      * @return external_single_structure
1823      * @since Moodle 2.6
1824      */
1825     public static function save_submission_returns() {
1826         return new external_warnings();
1827     }
1829     /**
1830      * Describes the parameters for save_grade
1831      * @return external_external_function_parameters
1832      * @since  Moodle 2.6
1833      */
1834     public static function save_grade_parameters() {
1835         global $CFG;
1836         require_once("$CFG->dirroot/grade/grading/lib.php");
1837         $instance = new assign(null, null, null);
1838         $pluginfeedbackparams = array();
1840         foreach ($instance->get_feedback_plugins() as $plugin) {
1841             if ($plugin->is_visible()) {
1842                 $pluginparams = $plugin->get_external_parameters();
1843                 if (!empty($pluginparams)) {
1844                     $pluginfeedbackparams = array_merge($pluginfeedbackparams, $pluginparams);
1845                 }
1846             }
1847         }
1849         $advancedgradingdata = array();
1850         $methods = array_keys(grading_manager::available_methods(false));
1851         foreach ($methods as $method) {
1852             require_once($CFG->dirroot.'/grade/grading/form/'.$method.'/lib.php');
1853             $details  = call_user_func('gradingform_'.$method.'_controller::get_external_instance_filling_details');
1854             if (!empty($details)) {
1855                 $items = array();
1856                 foreach ($details as $key => $value) {
1857                     $value->required = VALUE_OPTIONAL;
1858                     unset($value->content->keys['id']);
1859                     $items[$key] = new external_multiple_structure (new external_single_structure(
1860                         array(
1861                             'criterionid' => new external_value(PARAM_INT, 'criterion id'),
1862                             'fillings' => $value
1863                         )
1864                     ));
1865                 }
1866                 $advancedgradingdata[$method] = new external_single_structure($items, 'items', VALUE_OPTIONAL);
1867             }
1868         }
1870         return new external_function_parameters(
1871             array(
1872                 'assignmentid' => new external_value(PARAM_INT, 'The assignment id to operate on'),
1873                 'userid' => new external_value(PARAM_INT, 'The student id to operate on'),
1874                 'grade' => new external_value(PARAM_FLOAT, 'The new grade for this user. Ignored if advanced grading used'),
1875                 'attemptnumber' => new external_value(PARAM_INT, 'The attempt number (-1 means latest attempt)'),
1876                 'addattempt' => new external_value(PARAM_BOOL, 'Allow another attempt if the attempt reopen method is manual'),
1877                 'workflowstate' => new external_value(PARAM_ALPHA, 'The next marking workflow state'),
1878                 'applytoall' => new external_value(PARAM_BOOL, 'If true, this grade will be applied ' .
1879                                                                'to all members ' .
1880                                                                'of the group (for group assignments).'),
1881                 'plugindata' => new external_single_structure($pluginfeedbackparams, 'plugin data', VALUE_DEFAULT, array()),
1882                 'advancedgradingdata' => new external_single_structure($advancedgradingdata, 'advanced grading data',
1883                                                                        VALUE_DEFAULT, array())
1884             )
1885         );
1886     }
1888     /**
1889      * Save a student grade for a single assignment.
1890      *
1891      * @param int $assignmentid The id of the assignment
1892      * @param int $userid The id of the user
1893      * @param float $grade The grade (ignored if the assignment uses advanced grading)
1894      * @param int $attemptnumber The attempt number
1895      * @param bool $addattempt Allow another attempt
1896      * @param string $workflowstate New workflow state
1897      * @param bool $applytoall Apply the grade to all members of the group
1898      * @param array $plugindata Custom data used by plugins
1899      * @param array $advancedgradingdata Advanced grading data
1900      * @return null
1901      * @since Moodle 2.6
1902      */
1903     public static function save_grade($assignmentid,
1904                                       $userid,
1905                                       $grade,
1906                                       $attemptnumber,
1907                                       $addattempt,
1908                                       $workflowstate,
1909                                       $applytoall,
1910                                       $plugindata = array(),
1911                                       $advancedgradingdata = array()) {
1912         global $CFG, $USER;
1914         $params = self::validate_parameters(self::save_grade_parameters(),
1915                                             array('assignmentid' => $assignmentid,
1916                                                   'userid' => $userid,
1917                                                   'grade' => $grade,
1918                                                   'attemptnumber' => $attemptnumber,
1919                                                   'workflowstate' => $workflowstate,
1920                                                   'addattempt' => $addattempt,
1921                                                   'applytoall' => $applytoall,
1922                                                   'plugindata' => $plugindata,
1923                                                   'advancedgradingdata' => $advancedgradingdata));
1925         list($assignment, $course, $cm, $context) = self::validate_assign($params['assignmentid']);
1927         $gradedata = (object)$params['plugindata'];
1929         $gradedata->addattempt = $params['addattempt'];
1930         $gradedata->attemptnumber = $params['attemptnumber'];
1931         $gradedata->workflowstate = $params['workflowstate'];
1932         $gradedata->applytoall = $params['applytoall'];
1933         $gradedata->grade = $params['grade'];
1935         if (!empty($params['advancedgradingdata'])) {
1936             $advancedgrading = array();
1937             $criteria = reset($params['advancedgradingdata']);
1938             foreach ($criteria as $key => $criterion) {
1939                 $details = array();
1940                 foreach ($criterion as $value) {
1941                     foreach ($value['fillings'] as $filling) {
1942                         $details[$value['criterionid']] = $filling;
1943                     }
1944                 }
1945                 $advancedgrading[$key] = $details;
1946             }
1947             $gradedata->advancedgrading = $advancedgrading;
1948         }
1950         $assignment->save_grade($params['userid'], $gradedata);
1952         return null;
1953     }
1955     /**
1956      * Describes the return value for save_grade
1957      *
1958      * @return external_single_structure
1959      * @since Moodle 2.6
1960      */
1961     public static function save_grade_returns() {
1962         return null;
1963     }
1965     /**
1966      * Describes the parameters for save_grades
1967      * @return external_external_function_parameters
1968      * @since  Moodle 2.7
1969      */
1970     public static function save_grades_parameters() {
1971         global $CFG;
1972         require_once("$CFG->dirroot/grade/grading/lib.php");
1973         $instance = new assign(null, null, null);
1974         $pluginfeedbackparams = array();
1976         foreach ($instance->get_feedback_plugins() as $plugin) {
1977             if ($plugin->is_visible()) {
1978                 $pluginparams = $plugin->get_external_parameters();
1979                 if (!empty($pluginparams)) {
1980                     $pluginfeedbackparams = array_merge($pluginfeedbackparams, $pluginparams);
1981                 }
1982             }
1983         }
1985         $advancedgradingdata = array();
1986         $methods = array_keys(grading_manager::available_methods(false));
1987         foreach ($methods as $method) {
1988             require_once($CFG->dirroot.'/grade/grading/form/'.$method.'/lib.php');
1989             $details  = call_user_func('gradingform_'.$method.'_controller::get_external_instance_filling_details');
1990             if (!empty($details)) {
1991                 $items = array();
1992                 foreach ($details as $key => $value) {
1993                     $value->required = VALUE_OPTIONAL;
1994                     unset($value->content->keys['id']);
1995                     $items[$key] = new external_multiple_structure (new external_single_structure(
1996                         array(
1997                             'criterionid' => new external_value(PARAM_INT, 'criterion id'),
1998                             'fillings' => $value
1999                         )
2000                     ));
2001                 }
2002                 $advancedgradingdata[$method] = new external_single_structure($items, 'items', VALUE_OPTIONAL);
2003             }
2004         }
2006         return new external_function_parameters(
2007             array(
2008                 'assignmentid' => new external_value(PARAM_INT, 'The assignment id to operate on'),
2009                 'applytoall' => new external_value(PARAM_BOOL, 'If true, this grade will be applied ' .
2010                                                                'to all members ' .
2011                                                                'of the group (for group assignments).'),
2012                 'grades' => new external_multiple_structure(
2013                     new external_single_structure(
2014                         array (
2015                             'userid' => new external_value(PARAM_INT, 'The student id to operate on'),
2016                             'grade' => new external_value(PARAM_FLOAT, 'The new grade for this user. '.
2017                                                                        'Ignored if advanced grading used'),
2018                             'attemptnumber' => new external_value(PARAM_INT, 'The attempt number (-1 means latest attempt)'),
2019                             'addattempt' => new external_value(PARAM_BOOL, 'Allow another attempt if manual attempt reopen method'),
2020                             'workflowstate' => new external_value(PARAM_ALPHA, 'The next marking workflow state'),
2021                             'plugindata' => new external_single_structure($pluginfeedbackparams, 'plugin data',
2022                                                                           VALUE_DEFAULT, array()),
2023                             'advancedgradingdata' => new external_single_structure($advancedgradingdata, 'advanced grading data',
2024                                                                                    VALUE_DEFAULT, array())
2025                         )
2026                     )
2027                 )
2028             )
2029         );
2030     }
2032     /**
2033      * Save multiple student grades for a single assignment.
2034      *
2035      * @param int $assignmentid The id of the assignment
2036      * @param boolean $applytoall If set to true and this is a team assignment,
2037      * apply the grade to all members of the group
2038      * @param array $grades grade data for one or more students that includes
2039      *                  userid - The id of the student being graded
2040      *                  grade - The grade (ignored if the assignment uses advanced grading)
2041      *                  attemptnumber - The attempt number
2042      *                  addattempt - Allow another attempt
2043      *                  workflowstate - New workflow state
2044      *                  plugindata - Custom data used by plugins
2045      *                  advancedgradingdata - Optional Advanced grading data
2046      * @throws invalid_parameter_exception if multiple grades are supplied for
2047      * a team assignment that has $applytoall set to true
2048      * @return null
2049      * @since Moodle 2.7
2050      */
2051     public static function save_grades($assignmentid, $applytoall = false, $grades) {
2052         global $CFG, $USER;
2054         $params = self::validate_parameters(self::save_grades_parameters(),
2055                                             array('assignmentid' => $assignmentid,
2056                                                   'applytoall' => $applytoall,
2057                                                   'grades' => $grades));
2059         list($assignment, $course, $cm, $context) = self::validate_assign($params['assignmentid']);
2061         if ($assignment->get_instance()->teamsubmission && $params['applytoall']) {
2062             // Check that only 1 user per submission group is provided.
2063             $groupids = array();
2064             foreach ($params['grades'] as $gradeinfo) {
2065                 $group = $assignment->get_submission_group($gradeinfo['userid']);
2066                 if (in_array($group->id, $groupids)) {
2067                     throw new invalid_parameter_exception('Multiple grades for the same team have been supplied '
2068                                                           .' this is not permitted when the applytoall flag is set');
2069                 } else {
2070                     $groupids[] = $group->id;
2071                 }
2072             }
2073         }
2075         foreach ($params['grades'] as $gradeinfo) {
2076             $gradedata = (object)$gradeinfo['plugindata'];
2077             $gradedata->addattempt = $gradeinfo['addattempt'];
2078             $gradedata->attemptnumber = $gradeinfo['attemptnumber'];
2079             $gradedata->workflowstate = $gradeinfo['workflowstate'];
2080             $gradedata->applytoall = $params['applytoall'];
2081             $gradedata->grade = $gradeinfo['grade'];
2083             if (!empty($gradeinfo['advancedgradingdata'])) {
2084                 $advancedgrading = array();
2085                 $criteria = reset($gradeinfo['advancedgradingdata']);
2086                 foreach ($criteria as $key => $criterion) {
2087                     $details = array();
2088                     foreach ($criterion as $value) {
2089                         foreach ($value['fillings'] as $filling) {
2090                             $details[$value['criterionid']] = $filling;
2091                         }
2092                     }
2093                     $advancedgrading[$key] = $details;
2094                 }
2095                 $gradedata->advancedgrading = $advancedgrading;
2096             }
2097             $assignment->save_grade($gradeinfo['userid'], $gradedata);
2098         }
2100         return null;
2101     }
2103     /**
2104      * Describes the return value for save_grades
2105      *
2106      * @return external_single_structure
2107      * @since Moodle 2.7
2108      */
2109     public static function save_grades_returns() {
2110         return null;
2111     }
2113     /**
2114      * Describes the parameters for copy_previous_attempt
2115      * @return external_function_parameters
2116      * @since  Moodle 2.6
2117      */
2118     public static function copy_previous_attempt_parameters() {
2119         return new external_function_parameters(
2120             array(
2121                 'assignmentid' => new external_value(PARAM_INT, 'The assignment id to operate on'),
2122             )
2123         );
2124     }
2126     /**
2127      * Copy a students previous attempt to a new attempt.
2128      *
2129      * @param int $assignmentid
2130      * @return array of warnings to indicate any errors.
2131      * @since Moodle 2.6
2132      */
2133     public static function copy_previous_attempt($assignmentid) {
2135         $params = self::validate_parameters(self::copy_previous_attempt_parameters(),
2136                                             array('assignmentid' => $assignmentid));
2138         list($assignment, $course, $cm, $context) = self::validate_assign($params['assignmentid']);
2140         $notices = array();
2142         $assignment->copy_previous_attempt($notices);
2144         $warnings = array();
2145         foreach ($notices as $notice) {
2146             $warnings[] = self::generate_warning($assignmentid,
2147                                                  'couldnotcopyprevioussubmission',
2148                                                  $notice);
2149         }
2151         return $warnings;
2152     }
2154     /**
2155      * Describes the return value for save_submission
2156      *
2157      * @return external_single_structure
2158      * @since Moodle 2.6
2159      */
2160     public static function copy_previous_attempt_returns() {
2161         return new external_warnings();
2162     }
2164     /**
2165      * Returns description of method parameters
2166      *
2167      * @return external_function_parameters
2168      * @since Moodle 3.0
2169      */
2170     public static function view_grading_table_parameters() {
2171         return new external_function_parameters(
2172             array(
2173                 'assignid' => new external_value(PARAM_INT, 'assign instance id')
2174             )
2175         );
2176     }
2178     /**
2179      * Trigger the grading_table_viewed event.
2180      *
2181      * @param int $assignid the assign instance id
2182      * @return array of warnings and status result
2183      * @since Moodle 3.0
2184      * @throws moodle_exception
2185      */
2186     public static function view_grading_table($assignid) {
2188         $params = self::validate_parameters(self::view_grading_table_parameters(),
2189                                             array(
2190                                                 'assignid' => $assignid
2191                                             ));
2192         $warnings = array();
2194         list($assign, $course, $cm, $context) = self::validate_assign($params['assignid']);
2196         $assign->require_view_grades();
2197         \mod_assign\event\grading_table_viewed::create_from_assign($assign)->trigger();
2199         $result = array();
2200         $result['status'] = true;
2201         $result['warnings'] = $warnings;
2202         return $result;
2203     }
2205     /**
2206      * Returns description of method result value
2207      *
2208      * @return external_description
2209      * @since Moodle 3.0
2210      */
2211     public static function view_grading_table_returns() {
2212         return new external_single_structure(
2213             array(
2214                 'status' => new external_value(PARAM_BOOL, 'status: true if success'),
2215                 'warnings' => new external_warnings()
2216             )
2217         );
2218     }
2220     /**
2221      * Describes the parameters for view_submission_status.
2222      *
2223      * @return external_external_function_parameters
2224      * @since Moodle 3.1
2225      */
2226     public static function view_submission_status_parameters() {
2227         return new external_function_parameters (
2228             array(
2229                 'assignid' => new external_value(PARAM_INT, 'assign instance id'),
2230             )
2231         );
2232     }
2234     /**
2235      * Trigger the submission status viewed event.
2236      *
2237      * @param int $assignid assign instance id
2238      * @return array of warnings and status result
2239      * @since Moodle 3.1
2240      */
2241     public static function view_submission_status($assignid) {
2243         $warnings = array();
2244         $params = array(
2245             'assignid' => $assignid,
2246         );
2247         $params = self::validate_parameters(self::view_submission_status_parameters(), $params);
2249         list($assign, $course, $cm, $context) = self::validate_assign($params['assignid']);
2251         \mod_assign\event\submission_status_viewed::create_from_assign($assign)->trigger();
2253         $result = array();
2254         $result['status'] = true;
2255         $result['warnings'] = $warnings;
2256         return $result;
2257     }
2259     /**
2260      * Describes the view_submission_status return value.
2261      *
2262      * @return external_single_structure
2263      * @since Moodle 3.1
2264      */
2265     public static function view_submission_status_returns() {
2266         return new external_single_structure(
2267             array(
2268                 'status' => new external_value(PARAM_BOOL, 'status: true if success'),
2269                 'warnings' => new external_warnings(),
2270             )
2271         );
2272     }
2274     /**
2275      * Describes the parameters for get_submission_status.
2276      *
2277      * @return external_external_function_parameters
2278      * @since Moodle 3.1
2279      */
2280     public static function get_submission_status_parameters() {
2281         return new external_function_parameters (
2282             array(
2283                 'assignid' => new external_value(PARAM_INT, 'assignment instance id'),
2284                 'userid' => new external_value(PARAM_INT, 'user id (empty for current user)', VALUE_DEFAULT, 0),
2285             )
2286         );
2287     }
2289     /**
2290      * Returns information about an assignment submission status for a given user.
2291      *
2292      * @param int $assignid assignment instance id
2293      * @param int $userid user id (empty for current user)
2294      * @return array of warnings and grading, status, feedback and previous attempts information
2295      * @since Moodle 3.1
2296      * @throws required_capability_exception
2297      */
2298     public static function get_submission_status($assignid, $userid = 0) {
2299         global $USER;
2301         $warnings = array();
2303         $params = array(
2304             'assignid' => $assignid,
2305             'userid' => $userid,
2306         );
2307         $params = self::validate_parameters(self::get_submission_status_parameters(), $params);
2309         list($assign, $course, $cm, $context) = self::validate_assign($params['assignid']);
2311         // Default value for userid.
2312         if (empty($params['userid'])) {
2313             $params['userid'] = $USER->id;
2314         }
2315         $user = core_user::get_user($params['userid'], '*', MUST_EXIST);
2316         core_user::require_active_user($user);
2318         if (!$assign->can_view_submission($user->id)) {
2319             throw new required_capability_exception($context, 'mod/assign:viewgrades', 'nopermission', '');
2320         }
2322         $gradingsummary = $lastattempt = $feedback = $previousattempts = null;
2324         // Get the renderable since it contais all the info we need.
2325         if ($assign->can_view_grades()) {
2326             $gradingsummary = $assign->get_assign_grading_summary_renderable();
2327         }
2329         // Retrieve the rest of the renderable objects.
2330         if (has_capability('mod/assign:submit', $assign->get_context(), $user)) {
2331             $lastattempt = $assign->get_assign_submission_status_renderable($user, true);
2332         }
2334         $feedback = $assign->get_assign_feedback_status_renderable($user);
2336         $previousattempts = $assign->get_assign_attempt_history_renderable($user);
2338         // Now, build the result.
2339         $result = array();
2341         // First of all, grading summary, this is suitable for teachers/managers.
2342         if ($gradingsummary) {
2343             $result['gradingsummary'] = $gradingsummary;
2344         }
2346         // Did we submit anything?
2347         if ($lastattempt) {
2348             $submissionplugins = $assign->get_submission_plugins();
2350             if (empty($lastattempt->submission)) {
2351                 unset($lastattempt->submission);
2352             } else {
2353                 $lastattempt->submission->plugins = self::get_plugins_data($assign, $submissionplugins, $lastattempt->submission);
2354             }
2356             if (empty($lastattempt->teamsubmission)) {
2357                 unset($lastattempt->teamsubmission);
2358             } else {
2359                 $lastattempt->teamsubmission->plugins = self::get_plugins_data($assign, $submissionplugins,
2360                                                                                 $lastattempt->teamsubmission);
2361             }
2363             // We need to change the type of some of the structures retrieved from the renderable.
2364             if (!empty($lastattempt->submissiongroup)) {
2365                 $lastattempt->submissiongroup = $lastattempt->submissiongroup->id;
2366             } else {
2367                 unset($lastattempt->submissiongroup);
2368             }
2370             if (!empty($lastattempt->usergroups)) {
2371                 $lastattempt->usergroups = array_keys($lastattempt->usergroups);
2372             }
2373             // We cannot use array_keys here.
2374             if (!empty($lastattempt->submissiongroupmemberswhoneedtosubmit)) {
2375                 $lastattempt->submissiongroupmemberswhoneedtosubmit = array_map(
2376                                                                             function($e){
2377                                                                                 return $e->id;
2378                                                                             },
2379                                                                             $lastattempt->submissiongroupmemberswhoneedtosubmit);
2380             }
2382             // Can edit its own submission?
2383             $lastattempt->caneditowner = $assign->submissions_open($user->id) && $assign->is_any_submission_plugin_enabled();
2385             $result['lastattempt'] = $lastattempt;
2386         }
2388         // The feedback for our latest submission.
2389         if ($feedback) {
2390             if ($feedback->grade) {
2391                 $feedbackplugins = $assign->get_feedback_plugins();
2392                 $feedback->plugins = self::get_plugins_data($assign, $feedbackplugins, $feedback->grade);
2393             } else {
2394                 unset($feedback->plugins);
2395                 unset($feedback->grade);
2396             }
2398             $result['feedback'] = $feedback;
2399         }
2401         // Retrieve only previous attempts.
2402         if ($previousattempts and count($previousattempts->submissions) > 1) {
2403             // Don't show the last one because it is the current submission.
2404             array_pop($previousattempts->submissions);
2406             // Show newest to oldest.
2407             $previousattempts->submissions = array_reverse($previousattempts->submissions);
2409             foreach ($previousattempts->submissions as $i => $submission) {
2410                 $attempt = array();
2412                 $grade = null;
2413                 foreach ($previousattempts->grades as $onegrade) {
2414                     if ($onegrade->attemptnumber == $submission->attemptnumber) {
2415                         $grade = $onegrade;
2416                         break;
2417                     }
2418                 }
2420                 $attempt['attemptnumber'] = $submission->attemptnumber;
2422                 if ($submission) {
2423                     $submission->plugins = self::get_plugins_data($assign, $previousattempts->submissionplugins, $submission);
2424                     $attempt['submission'] = $submission;
2425                 }
2427                 if ($grade) {
2428                     // From object to id.
2429                     $grade->grader = $grade->grader->id;
2430                     $feedbackplugins = self::get_plugins_data($assign, $previousattempts->feedbackplugins, $grade);
2432                     $attempt['grade'] = $grade;
2433                     $attempt['feedbackplugins'] = $feedbackplugins;
2434                 }
2435                 $result['previousattempts'][] = $attempt;
2436             }
2437         }
2439         $result['warnings'] = $warnings;
2440         return $result;
2441     }
2443     /**
2444      * Describes the get_submission_status return value.
2445      *
2446      * @return external_single_structure
2447      * @since Moodle 3.1
2448      */
2449     public static function get_submission_status_returns() {
2450         return new external_single_structure(
2451             array(
2452                 'gradingsummary' => new external_single_structure(
2453                     array(
2454                         'participantcount' => new external_value(PARAM_INT, 'Number of users who can submit.'),
2455                         'submissiondraftscount' => new external_value(PARAM_INT, 'Number of submissions in draft status.'),
2456                         'submissiondraftscount' => new external_value(PARAM_INT, 'Number of submissions in draft status.'),
2457                         'submissionsenabled' => new external_value(PARAM_BOOL, 'Whether submissions are enabled or not.'),
2458                         'submissionssubmittedcount' => new external_value(PARAM_INT, 'Number of submissions in submitted status.'),
2459                         'submissionsneedgradingcount' => new external_value(PARAM_INT, 'Number of submissions that need grading.'),
2460                         'warnofungroupedusers' => new external_value(PARAM_BOOL, 'Whether we need to warn people that there
2461                                                                         are users without groups.'),
2462                     ), 'Grading information.', VALUE_OPTIONAL
2463                 ),
2464                 'lastattempt' => new external_single_structure(
2465                     array(
2466                         'submission' => self::get_submission_structure(VALUE_OPTIONAL),
2467                         'teamsubmission' => self::get_submission_structure(VALUE_OPTIONAL),
2468                         'submissiongroup' => new external_value(PARAM_INT, 'The submission group id (for group submissions only).',
2469                                                                 VALUE_OPTIONAL),
2470                         'submissiongroupmemberswhoneedtosubmit' => new external_multiple_structure(
2471                             new external_value(PARAM_INT, 'USER id.'),
2472                             'List of users who still need to submit (for group submissions only).',
2473                             VALUE_OPTIONAL
2474                         ),
2475                         'submissionsenabled' => new external_value(PARAM_BOOL, 'Whether submissions are enabled or not.'),
2476                         'locked' => new external_value(PARAM_BOOL, 'Whether new submissions are locked.'),
2477                         'graded' => new external_value(PARAM_BOOL, 'Whether the submission is graded.'),
2478                         'canedit' => new external_value(PARAM_BOOL, 'Whether the user can edit the current submission.'),
2479                         'caneditowner' => new external_value(PARAM_BOOL, 'Whether the owner of the submission can edit it.'),
2480                         'cansubmit' => new external_value(PARAM_BOOL, 'Whether the user can submit.'),
2481                         'extensionduedate' => new external_value(PARAM_INT, 'Extension due date.'),
2482                         'blindmarking' => new external_value(PARAM_BOOL, 'Whether blind marking is enabled.'),
2483                         'gradingstatus' => new external_value(PARAM_ALPHANUMEXT, 'Grading status.'),
2484                         'usergroups' => new external_multiple_structure(
2485                             new external_value(PARAM_INT, 'Group id.'), 'User groups in the course.'
2486                         ),
2487                     ), 'Last attempt information.', VALUE_OPTIONAL
2488                 ),
2489                 'feedback' => new external_single_structure(
2490                     array(
2491                         'grade' => self::get_grade_structure(VALUE_OPTIONAL),
2492                         'gradefordisplay' => new external_value(PARAM_RAW, 'Grade rendered into a format suitable for display.'),
2493                         'gradeddate' => new external_value(PARAM_INT, 'The date the user was graded.'),
2494                         'plugins' => new external_multiple_structure(self::get_plugin_structure(), 'Plugins info.', VALUE_OPTIONAL),
2495                     ), 'Feedback for the last attempt.', VALUE_OPTIONAL
2496                 ),
2497                 'previousattempts' => new external_multiple_structure(
2498                     new external_single_structure(
2499                         array(
2500                             'attemptnumber' => new external_value(PARAM_INT, 'Attempt number.'),
2501                             'submission' => self::get_submission_structure(VALUE_OPTIONAL),
2502                             'grade' => self::get_grade_structure(VALUE_OPTIONAL),
2503                             'feedbackplugins' => new external_multiple_structure(self::get_plugin_structure(), 'Feedback info.',
2504                                                                                     VALUE_OPTIONAL),
2505                         )
2506                     ), 'List all the previous attempts did by the user.', VALUE_OPTIONAL
2507                 ),
2508                 'warnings' => new external_warnings(),
2509             )
2510         );
2511     }
2513     /**
2514      * Returns description of method parameters
2515      *
2516      * @return external_function_parameters
2517      * @since Moodle 3.1
2518      */
2519     public static function list_participants_parameters() {
2520         return new external_function_parameters(
2521             array(
2522                 'assignid' => new external_value(PARAM_INT, 'assign instance id'),
2523                 'groupid' => new external_value(PARAM_INT, 'group id'),
2524                 'filter' => new external_value(PARAM_RAW, 'search string to filter the results'),
2525                 'skip' => new external_value(PARAM_INT, 'number of records to skip', VALUE_DEFAULT, 0),
2526                 'limit' => new external_value(PARAM_INT, 'maximum number of records to return', VALUE_DEFAULT, 0),
2527                 'onlyids' => new external_value(PARAM_BOOL, 'Do not return all user fields', VALUE_DEFAULT, false),
2528                 'includeenrolments' => new external_value(PARAM_BOOL, 'Do return courses where the user is enrolled',
2529                                                           VALUE_DEFAULT, true)
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      * @param bool $onlyids Only return user ids.
2543      * @param bool $includeenrolments Return courses where the user is enrolled.
2544      * @return array of warnings and status result
2545      * @since Moodle 3.1
2546      * @throws moodle_exception
2547      */
2548     public static function list_participants($assignid, $groupid, $filter, $skip, $limit, $onlyids, $includeenrolments) {
2549         global $DB, $CFG;
2550         require_once($CFG->dirroot . "/mod/assign/locallib.php");
2551         require_once($CFG->dirroot . "/user/lib.php");
2553         $params = self::validate_parameters(self::list_participants_parameters(),
2554                                             array(
2555                                                 'assignid' => $assignid,
2556                                                 'groupid' => $groupid,
2557                                                 'filter' => $filter,
2558                                                 'skip' => $skip,
2559                                                 'limit' => $limit,
2560                                                 'onlyids' => $onlyids,
2561                                                 'includeenrolments' => $includeenrolments
2562                                             ));
2563         $warnings = array();
2565         list($assign, $course, $cm, $context) = self::validate_assign($params['assignid']);
2567         require_capability('mod/assign:view', $context);
2569         $assign->require_view_grades();
2571         $participants = array();
2572         if (groups_group_visible($params['groupid'], $course, $cm)) {
2573             $participants = $assign->list_participants_with_filter_status_and_group($params['groupid']);
2574         }
2576         $userfields = user_get_default_fields();
2577         if (!$params['includeenrolments']) {
2578             // Remove enrolled courses from users fields to be returned.
2579             $key = array_search('enrolledcourses', $userfields);
2580             if ($key !== false) {
2581                 unset($userfields[$key]);
2582             } else {
2583                 throw new moodle_exception('invaliduserfield', 'error', '', 'enrolledcourses');
2584             }
2585         }
2587         $result = array();
2588         $index = 0;
2589         foreach ($participants as $record) {
2590             // Preserve the fullname set by the assignment.
2591             $fullname = $record->fullname;
2592             $searchable = $fullname;
2593             $match = false;
2594             if (empty($filter)) {
2595                 $match = true;
2596             } else {
2597                 $filter = core_text::strtolower($filter);
2598                 $value = core_text::strtolower($searchable);
2599                 if (is_string($value) && (core_text::strpos($value, $filter) !== false)) {
2600                     $match = true;
2601                 }
2602             }
2603             if ($match) {
2604                 $index++;
2605                 if ($index <= $params['skip']) {
2606                     continue;
2607                 }
2608                 if (($params['limit'] > 0) && (($index - $params['skip']) > $params['limit'])) {
2609                     break;
2610                 }
2611                 // Now we do the expensive lookup of user details because we completed the filtering.
2612                 if (!$assign->is_blind_marking() && !$params['onlyids']) {
2613                     $userdetails = user_get_user_details($record, $course, $userfields);
2614                 } else {
2615                     $userdetails = array('id' => $record->id);
2616                 }
2617                 $userdetails['fullname'] = $fullname;
2618                 $userdetails['submitted'] = $record->submitted;
2619                 $userdetails['requiregrading'] = $record->requiregrading;
2620                 if (!empty($record->groupid)) {
2621                     $userdetails['groupid'] = $record->groupid;
2622                 }
2623                 if (!empty($record->groupname)) {
2624                     $userdetails['groupname'] = $record->groupname;
2625                 }
2627                 $result[] = $userdetails;
2628             }
2629         }
2630         return $result;
2631     }
2633     /**
2634      * Returns the description of the results of the mod_assign_external::list_participants() method.
2635      *
2636      * @return external_description
2637      * @since Moodle 3.1
2638      */
2639     public static function list_participants_returns() {
2640         // Get user description.
2641         $userdesc = core_user_external::user_description();
2642         // List unneeded properties.
2643         $unneededproperties = [
2644             'auth', 'confirmed', 'lang', 'calendartype', 'theme', 'timezone', 'mailformat'
2645         ];
2646         // Remove unneeded properties for consistency with the previous version.
2647         foreach ($unneededproperties as $prop) {
2648             unset($userdesc->keys[$prop]);
2649         }
2651         // Override property attributes for consistency with the previous version.
2652         $userdesc->keys['fullname']->type = PARAM_NOTAGS;
2653         $userdesc->keys['profileimageurlsmall']->required = VALUE_OPTIONAL;
2654         $userdesc->keys['profileimageurl']->required = VALUE_OPTIONAL;
2655         $userdesc->keys['email']->desc = 'Email address';
2656         $userdesc->keys['idnumber']->desc = 'The idnumber of the user';
2658         // Define other keys.
2659         $otherkeys = [
2660             'groups' => new external_multiple_structure(
2661                 new external_single_structure(
2662                     [
2663                         'id' => new external_value(PARAM_INT, 'group id'),
2664                         'name' => new external_value(PARAM_RAW, 'group name'),
2665                         'description' => new external_value(PARAM_RAW, 'group description'),
2666                     ]
2667                 ), 'user groups', VALUE_OPTIONAL
2668             ),
2669             'roles' => new external_multiple_structure(
2670                 new external_single_structure(
2671                     [
2672                         'roleid' => new external_value(PARAM_INT, 'role id'),
2673                         'name' => new external_value(PARAM_RAW, 'role name'),
2674                         'shortname' => new external_value(PARAM_ALPHANUMEXT, 'role shortname'),
2675                         'sortorder' => new external_value(PARAM_INT, 'role sortorder')
2676                     ]
2677                 ), 'user roles', VALUE_OPTIONAL
2678             ),
2679             'enrolledcourses' => new external_multiple_structure(
2680                 new external_single_structure(
2681                     [
2682                         'id' => new external_value(PARAM_INT, 'Id of the course'),
2683                         'fullname' => new external_value(PARAM_RAW, 'Fullname of the course'),
2684                         'shortname' => new external_value(PARAM_RAW, 'Shortname of the course')
2685                     ]
2686                 ), 'Courses where the user is enrolled - limited by which courses the user is able to see', VALUE_OPTIONAL
2687             ),
2688             'submitted' => new external_value(PARAM_BOOL, 'have they submitted their assignment'),
2689             'requiregrading' => new external_value(PARAM_BOOL, 'is their submission waiting for grading'),
2690             'groupid' => new external_value(PARAM_INT, 'for group assignments this is the group id', VALUE_OPTIONAL),
2691             'groupname' => new external_value(PARAM_NOTAGS, 'for group assignments this is the group name', VALUE_OPTIONAL),
2692         ];
2694         // Merge keys.
2695         $userdesc->keys = array_merge($userdesc->keys, $otherkeys);
2696         return new external_multiple_structure($userdesc);
2697     }
2699     /**
2700      * Returns description of method parameters
2701      *
2702      * @return external_function_parameters
2703      * @since Moodle 3.1
2704      */
2705     public static function get_participant_parameters() {
2706         return new external_function_parameters(
2707             array(
2708                 'assignid' => new external_value(PARAM_INT, 'assign instance id'),
2709                 'userid' => new external_value(PARAM_INT, 'user id'),
2710                 'embeduser' => new external_value(PARAM_BOOL, 'user id', VALUE_DEFAULT, false),
2711             )
2712         );
2713     }
2715     /**
2716      * Get the user participating in the given assignment. An error with code 'usernotincourse'
2717      * is thrown is the user isn't a participant of the given assignment.
2718      *
2719      * @param int $assignid the assign instance id
2720      * @param int $userid the user id
2721      * @param bool $embeduser return user details (only applicable if not blind marking)
2722      * @return array of warnings and status result
2723      * @since Moodle 3.1
2724      * @throws moodle_exception
2725      */
2726     public static function get_participant($assignid, $userid, $embeduser) {
2727         global $DB, $CFG;
2728         require_once($CFG->dirroot . "/mod/assign/locallib.php");
2729         require_once($CFG->dirroot . "/user/lib.php");
2731         $params = self::validate_parameters(self::get_participant_parameters(), array(
2732             'assignid' => $assignid,
2733             'userid' => $userid,
2734             'embeduser' => $embeduser
2735         ));
2737         list($assign, $course, $cm, $context) = self::validate_assign($params['assignid']);
2738         $assign->require_view_grades();
2740         $participant = $assign->get_participant($params['userid']);
2742         // Update assign with override information.
2743         $assign->update_effective_access($params['userid']);
2745         if (!$participant) {
2746             // No participant found so we can return early.
2747             throw new moodle_exception('usernotincourse');
2748         }
2750         $return = array(
2751             'id' => $participant->id,
2752             'fullname' => $participant->fullname,
2753             'submitted' => $participant->submitted,
2754             'requiregrading' => $participant->requiregrading,
2755             'blindmarking' => $assign->is_blind_marking(),
2756             'allowsubmissionsfromdate' => $assign->get_instance()->allowsubmissionsfromdate,
2757             'duedate' => $assign->get_instance()->duedate,
2758             'cutoffdate' => $assign->get_instance()->cutoffdate,
2759             'duedatestr' => userdate($assign->get_instance()->duedate, get_string('strftimedatetime', 'langconfig')),
2760         );
2762         if (!empty($participant->groupid)) {
2763             $return['groupid'] = $participant->groupid;
2764         }
2765         if (!empty($participant->groupname)) {
2766             $return['groupname'] = $participant->groupname;
2767         }
2769         // Skip the expensive lookup of user detail if we're blind marking or the caller
2770         // hasn't asked for user details to be embedded.
2771         if (!$assign->is_blind_marking() && $embeduser) {
2772             $return['user'] = user_get_user_details($participant, $course);
2773         }
2775         return $return;
2776     }
2778     /**
2779      * Returns description of method result value
2780      *
2781      * @return external_description
2782      * @since Moodle 3.1
2783      */
2784     public static function get_participant_returns() {
2785         $userdescription = core_user_external::user_description();
2786         $userdescription->default = [];
2787         $userdescription->required = VALUE_OPTIONAL;
2789         return new external_single_structure(array(
2790             'id' => new external_value(PARAM_INT, 'ID of the user'),
2791             'fullname' => new external_value(PARAM_NOTAGS, 'The fullname of the user'),
2792             'submitted' => new external_value(PARAM_BOOL, 'have they submitted their assignment'),
2793             'requiregrading' => new external_value(PARAM_BOOL, 'is their submission waiting for grading'),
2794             'blindmarking' => new external_value(PARAM_BOOL, 'is blind marking enabled for this assignment'),
2795             'allowsubmissionsfromdate' => new external_value(PARAM_INT, 'allowsubmissionsfromdate for the user'),
2796             'duedate' => new external_value(PARAM_INT, 'duedate for the user'),
2797             'cutoffdate' => new external_value(PARAM_INT, 'cutoffdate for the user'),
2798             'duedatestr' => new external_value(PARAM_TEXT, 'duedate for the user'),
2799             'groupid' => new external_value(PARAM_INT, 'for group assignments this is the group id', VALUE_OPTIONAL),
2800             'groupname' => new external_value(PARAM_NOTAGS, 'for group assignments this is the group name', VALUE_OPTIONAL),
2801             'user' => $userdescription,
2802         ));
2803     }
2805     /**
2806      * Utility function for validating an assign.
2807      *
2808      * @param int $assignid assign instance id
2809      * @return array array containing the assign, course, context and course module objects
2810      * @since  Moodle 3.2
2811      */
2812     protected static function validate_assign($assignid) {
2813         global $DB;
2815         // Request and permission validation.
2816         $assign = $DB->get_record('assign', array('id' => $assignid), 'id', MUST_EXIST);
2817         list($course, $cm) = get_course_and_cm_from_instance($assign, 'assign');
2819         $context = context_module::instance($cm->id);
2820         // Please, note that is not required to check mod/assign:view because is done by validate_context->require_login.
2821         self::validate_context($context);
2822         $assign = new assign($context, $cm, $course);
2824         return array($assign, $course, $cm, $context);
2825     }
2827     /**
2828      * Describes the parameters for view_assign.
2829      *
2830      * @return external_external_function_parameters
2831      * @since Moodle 3.2
2832      */
2833     public static function view_assign_parameters() {
2834         return new external_function_parameters (
2835             array(
2836                 'assignid' => new external_value(PARAM_INT, 'assign instance id'),
2837             )
2838         );
2839     }
2841     /**
2842      * Update the module completion status.
2843      *
2844      * @param int $assignid assign instance id
2845      * @return array of warnings and status result
2846      * @since Moodle 3.2
2847      */
2848     public static function view_assign($assignid) {
2849         $warnings = array();
2850         $params = array(
2851             'assignid' => $assignid,
2852         );
2853         $params = self::validate_parameters(self::view_assign_parameters(), $params);
2855         list($assign, $course, $cm, $context) = self::validate_assign($params['assignid']);
2857         $assign->set_module_viewed();
2859         $result = array();
2860         $result['status'] = true;
2861         $result['warnings'] = $warnings;
2862         return $result;
2863     }
2865     /**
2866      * Describes the view_assign return value.
2867      *
2868      * @return external_single_structure
2869      * @since Moodle 3.2
2870      */
2871     public static function view_assign_returns() {
2872         return new external_single_structure(
2873             array(
2874                 'status' => new external_value(PARAM_BOOL, 'status: true if success'),
2875                 'warnings' => new external_warnings(),
2876             )
2877         );
2878     }