MDL-52924 mod_assign: New WS mod_assign_get_submission_status
[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/mod/assign/locallib.php");
31 /**
32  * Assign functions
33  * @copyright 2012 Paul Charsley
34  * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
35  */
36 class mod_assign_external extends external_api {
38     /**
39      * Generate a warning in a standard structure for a known failure.
40      *
41      * @param int $assignmentid - The assignment
42      * @param string $warningcode - The key for the warning message
43      * @param string $detail - A description of the error
44      * @return array - Warning structure containing item, itemid, warningcode, message
45      */
46     private static function generate_warning($assignmentid, $warningcode, $detail) {
47         $warningmessages = array(
48             'couldnotlock'=>'Could not lock the submission for this user.',
49             'couldnotunlock'=>'Could not unlock the submission for this user.',
50             'couldnotsubmitforgrading'=>'Could not submit assignment for grading.',
51             'couldnotrevealidentities'=>'Could not reveal identities.',
52             'couldnotgrantextensions'=>'Could not grant submission date extensions.',
53             'couldnotrevert'=>'Could not revert submission to draft.',
54             'invalidparameters'=>'Invalid parameters.',
55             'couldnotsavesubmission'=>'Could not save submission.',
56             'couldnotsavegrade'=>'Could not save grade.'
57         );
59         $message = $warningmessages[$warningcode];
60         if (empty($message)) {
61             $message = 'Unknown warning type.';
62         }
64         return array('item'=>$detail,
65                      'itemid'=>$assignmentid,
66                      'warningcode'=>$warningcode,
67                      'message'=>$message);
68     }
70     /**
71      * Describes the parameters for get_grades
72      * @return external_external_function_parameters
73      * @since  Moodle 2.4
74      */
75     public static function get_grades_parameters() {
76         return new external_function_parameters(
77             array(
78                 'assignmentids' => new external_multiple_structure(
79                     new external_value(PARAM_INT, 'assignment id'),
80                     '1 or more assignment ids',
81                     VALUE_REQUIRED),
82                 'since' => new external_value(PARAM_INT,
83                           'timestamp, only return records where timemodified >= since',
84                           VALUE_DEFAULT, 0)
85             )
86         );
87     }
89     /**
90      * Returns grade information from assign_grades for the requested assignment ids
91      * @param int[] $assignmentids
92      * @param int $since only return records with timemodified >= since
93      * @return array of grade records for each requested assignment
94      * @since  Moodle 2.4
95      */
96     public static function get_grades($assignmentids, $since = 0) {
97         global $DB;
98         $params = self::validate_parameters(self::get_grades_parameters(),
99                         array('assignmentids' => $assignmentids,
100                               'since' => $since));
102         $assignments = array();
103         $warnings = array();
104         $requestedassignmentids = $params['assignmentids'];
106         // Check the user is allowed to get the grades for the assignments requested.
107         $placeholders = array();
108         list($sqlassignmentids, $placeholders) = $DB->get_in_or_equal($requestedassignmentids, SQL_PARAMS_NAMED);
109         $sql = "SELECT cm.id, cm.instance FROM {course_modules} cm JOIN {modules} md ON md.id = cm.module ".
110                "WHERE md.name = :modname AND cm.instance ".$sqlassignmentids;
111         $placeholders['modname'] = 'assign';
112         $cms = $DB->get_records_sql($sql, $placeholders);
113         foreach ($cms as $cm) {
114             try {
115                 $context = context_module::instance($cm->id);
116                 self::validate_context($context);
117                 require_capability('mod/assign:grade', $context);
118             } catch (Exception $e) {
119                 $requestedassignmentids = array_diff($requestedassignmentids, array($cm->instance));
120                 $warning = array();
121                 $warning['item'] = 'assignment';
122                 $warning['itemid'] = $cm->instance;
123                 $warning['warningcode'] = '1';
124                 $warning['message'] = 'No access rights in module context';
125                 $warnings[] = $warning;
126             }
127         }
129         // Create the query and populate an array of grade records from the recordset results.
130         if (count ($requestedassignmentids) > 0) {
131             $placeholders = array();
132             list($inorequalsql, $placeholders) = $DB->get_in_or_equal($requestedassignmentids, SQL_PARAMS_NAMED);
134             $sql = "SELECT ag.id,
135                            ag.assignment,
136                            ag.userid,
137                            ag.timecreated,
138                            ag.timemodified,
139                            ag.grader,
140                            ag.grade,
141                            ag.attemptnumber
142                       FROM {assign_grades} ag, {assign_submission} s
143                      WHERE s.assignment $inorequalsql
144                        AND s.userid = ag.userid
145                        AND s.latest = 1
146                        AND s.attemptnumber = ag.attemptnumber
147                        AND ag.timemodified  >= :since
148                        AND ag.assignment = s.assignment
149                   ORDER BY ag.assignment, ag.id";
151             $placeholders['since'] = $params['since'];
152             $rs = $DB->get_recordset_sql($sql, $placeholders);
153             $currentassignmentid = null;
154             $assignment = null;
155             foreach ($rs as $rd) {
156                 $grade = array();
157                 $grade['id'] = $rd->id;
158                 $grade['userid'] = $rd->userid;
159                 $grade['timecreated'] = $rd->timecreated;
160                 $grade['timemodified'] = $rd->timemodified;
161                 $grade['grader'] = $rd->grader;
162                 $grade['attemptnumber'] = $rd->attemptnumber;
163                 $grade['grade'] = (string)$rd->grade;
165                 if (is_null($currentassignmentid) || ($rd->assignment != $currentassignmentid )) {
166                     if (!is_null($assignment)) {
167                         $assignments[] = $assignment;
168                     }
169                     $assignment = array();
170                     $assignment['assignmentid'] = $rd->assignment;
171                     $assignment['grades'] = array();
172                     $requestedassignmentids = array_diff($requestedassignmentids, array($rd->assignment));
173                 }
174                 $assignment['grades'][] = $grade;
176                 $currentassignmentid = $rd->assignment;
177             }
178             if (!is_null($assignment)) {
179                 $assignments[] = $assignment;
180             }
181             $rs->close();
182         }
183         foreach ($requestedassignmentids as $assignmentid) {
184             $warning = array();
185             $warning['item'] = 'assignment';
186             $warning['itemid'] = $assignmentid;
187             $warning['warningcode'] = '3';
188             $warning['message'] = 'No grades found';
189             $warnings[] = $warning;
190         }
192         $result = array();
193         $result['assignments'] = $assignments;
194         $result['warnings'] = $warnings;
195         return $result;
196     }
198     /**
199      * Creates a grade single structure.
200      *
201      * @return external_single_structure a grade single structure.
202      * @since  Moodle 3.1
203      */
204     private static function get_grade_structure($required = VALUE_REQUIRED) {
205         return new external_single_structure(
206             array(
207                 'id'                => new external_value(PARAM_INT, 'grade id'),
208                 'assignment'        => new external_value(PARAM_INT, 'assignment id', VALUE_OPTIONAL),
209                 'userid'            => new external_value(PARAM_INT, 'student id'),
210                 'attemptnumber'     => new external_value(PARAM_INT, 'attempt number'),
211                 'timecreated'       => new external_value(PARAM_INT, 'grade creation time'),
212                 'timemodified'      => new external_value(PARAM_INT, 'grade last modified time'),
213                 'grader'            => new external_value(PARAM_INT, 'grader'),
214                 'grade'             => new external_value(PARAM_TEXT, 'grade'),
215                 'gradefordisplay'   => new external_value(PARAM_RAW, 'grade rendered into a format suitable for display',
216                                                             VALUE_OPTIONAL),
217             ), 'grade information', $required
218         );
219     }
221     /**
222      * Creates an assign_grades external_single_structure
223      * @return external_single_structure
224      * @since  Moodle 2.4
225      */
226     private static function assign_grades() {
227         return new external_single_structure(
228             array (
229                 'assignmentid'  => new external_value(PARAM_INT, 'assignment id'),
230                 'grades'        => new external_multiple_structure(self::get_grade_structure())
231             )
232         );
233     }
235     /**
236      * Describes the get_grades return value
237      * @return external_single_structure
238      * @since  Moodle 2.4
239      */
240     public static function get_grades_returns() {
241         return new external_single_structure(
242             array(
243                 'assignments' => new external_multiple_structure(self::assign_grades(), 'list of assignment grade information'),
244                 'warnings'      => new external_warnings('item is always \'assignment\'',
245                     'when errorcode is 3 then itemid is an assignment id. When errorcode is 1, itemid is a course module id',
246                     'errorcode can be 3 (no grades found) or 1 (no permission to get grades)')
247             )
248         );
249     }
251     /**
252      * Returns description of method parameters
253      *
254      * @return external_function_parameters
255      * @since  Moodle 2.4
256      */
257     public static function get_assignments_parameters() {
258         return new external_function_parameters(
259             array(
260                 'courseids' => new external_multiple_structure(
261                     new external_value(PARAM_INT, 'course id'),
262                     '0 or more course ids',
263                     VALUE_DEFAULT, array()
264                 ),
265                 'capabilities'  => new external_multiple_structure(
266                     new external_value(PARAM_CAPABILITY, 'capability'),
267                     'list of capabilities used to filter courses',
268                     VALUE_DEFAULT, array()
269                 )
270             )
271         );
272     }
274     /**
275      * Returns an array of courses the user is enrolled in, and for each course all of the assignments that the user can
276      * view within that course.
277      *
278      * @param array $courseids An optional array of course ids. If provided only assignments within the given course
279      * will be returned. If the user is not enrolled in a given course a warning will be generated and returned.
280      * @param array $capabilities An array of additional capability checks you wish to be made on the course context.
281      * @return An array of courses and warnings.
282      * @since  Moodle 2.4
283      */
284     public static function get_assignments($courseids = array(), $capabilities = array()) {
285         global $USER, $DB, $CFG;
287         $params = self::validate_parameters(
288             self::get_assignments_parameters(),
289             array('courseids' => $courseids, 'capabilities' => $capabilities)
290         );
292         $warnings = array();
293         $fields = 'sortorder,shortname,fullname,timemodified';
294         $courses = enrol_get_users_courses($USER->id, true, $fields);
295         // Used to test for ids that have been requested but can't be returned.
296         if (count($params['courseids']) > 0) {
297             foreach ($params['courseids'] as $courseid) {
298                 if (!in_array($courseid, array_keys($courses))) {
299                     unset($courses[$courseid]);
300                     $warnings[] = array(
301                         'item' => 'course',
302                         'itemid' => $courseid,
303                         'warningcode' => '2',
304                         'message' => 'User is not enrolled or does not have requested capability'
305                     );
306                 }
307             }
308         }
309         foreach ($courses as $id => $course) {
310             if (count($params['courseids']) > 0 && !in_array($id, $params['courseids'])) {
311                 unset($courses[$id]);
312             }
313             $context = context_course::instance($id);
314             try {
315                 self::validate_context($context);
316             } catch (Exception $e) {
317                 unset($courses[$id]);
318                 $warnings[] = array(
319                     'item' => 'course',
320                     'itemid' => $id,
321                     'warningcode' => '1',
322                     'message' => 'No access rights in course context '.$e->getMessage().$e->getTraceAsString()
323                 );
324                 continue;
325             }
326             if (count($params['capabilities']) > 0 && !has_all_capabilities($params['capabilities'], $context)) {
327                 unset($courses[$id]);
328             }
329         }
330         $extrafields='m.id as assignmentid, ' .
331                      'm.course, ' .
332                      'm.nosubmissions, ' .
333                      'm.submissiondrafts, ' .
334                      'm.sendnotifications, '.
335                      'm.sendlatenotifications, ' .
336                      'm.sendstudentnotifications, ' .
337                      'm.duedate, ' .
338                      'm.allowsubmissionsfromdate, '.
339                      'm.grade, ' .
340                      'm.timemodified, '.
341                      'm.completionsubmit, ' .
342                      'm.cutoffdate, ' .
343                      'm.teamsubmission, ' .
344                      'm.requireallteammemberssubmit, '.
345                      'm.teamsubmissiongroupingid, ' .
346                      'm.blindmarking, ' .
347                      'm.revealidentities, ' .
348                      'm.attemptreopenmethod, '.
349                      'm.maxattempts, ' .
350                      'm.markingworkflow, ' .
351                      'm.markingallocation, ' .
352                      'm.requiresubmissionstatement, '.
353                      'm.intro, '.
354                      'm.introformat';
355         $coursearray = array();
356         foreach ($courses as $id => $course) {
357             $assignmentarray = array();
358             // Get a list of assignments for the course.
359             if ($modules = get_coursemodules_in_course('assign', $courses[$id]->id, $extrafields)) {
360                 foreach ($modules as $module) {
361                     $context = context_module::instance($module->id);
362                     try {
363                         self::validate_context($context);
364                         require_capability('mod/assign:view', $context);
365                     } catch (Exception $e) {
366                         $warnings[] = array(
367                             'item' => 'module',
368                             'itemid' => $module->id,
369                             'warningcode' => '1',
370                             'message' => 'No access rights in module context'
371                         );
372                         continue;
373                     }
374                     $configrecords = $DB->get_recordset('assign_plugin_config', array('assignment' => $module->assignmentid));
375                     $configarray = array();
376                     foreach ($configrecords as $configrecord) {
377                         $configarray[] = array(
378                             'id' => $configrecord->id,
379                             'assignment' => $configrecord->assignment,
380                             'plugin' => $configrecord->plugin,
381                             'subtype' => $configrecord->subtype,
382                             'name' => $configrecord->name,
383                             'value' => $configrecord->value
384                         );
385                     }
386                     $configrecords->close();
388                     $assignment = array(
389                         'id' => $module->assignmentid,
390                         'cmid' => $module->id,
391                         'course' => $module->course,
392                         'name' => $module->name,
393                         'nosubmissions' => $module->nosubmissions,
394                         'submissiondrafts' => $module->submissiondrafts,
395                         'sendnotifications' => $module->sendnotifications,
396                         'sendlatenotifications' => $module->sendlatenotifications,
397                         'sendstudentnotifications' => $module->sendstudentnotifications,
398                         'duedate' => $module->duedate,
399                         'allowsubmissionsfromdate' => $module->allowsubmissionsfromdate,
400                         'grade' => $module->grade,
401                         'timemodified' => $module->timemodified,
402                         'completionsubmit' => $module->completionsubmit,
403                         'cutoffdate' => $module->cutoffdate,
404                         'teamsubmission' => $module->teamsubmission,
405                         'requireallteammemberssubmit' => $module->requireallteammemberssubmit,
406                         'teamsubmissiongroupingid' => $module->teamsubmissiongroupingid,
407                         'blindmarking' => $module->blindmarking,
408                         'revealidentities' => $module->revealidentities,
409                         'attemptreopenmethod' => $module->attemptreopenmethod,
410                         'maxattempts' => $module->maxattempts,
411                         'markingworkflow' => $module->markingworkflow,
412                         'markingallocation' => $module->markingallocation,
413                         'requiresubmissionstatement' => $module->requiresubmissionstatement,
414                         'configs' => $configarray
415                     );
417                     // Return or not intro and file attachments depending on the plugin settings.
418                     $assign = new assign($context, null, null);
420                     if ($assign->show_intro()) {
422                         list($assignment['intro'], $assignment['introformat']) = external_format_text($module->intro,
423                             $module->introformat, $context->id, 'mod_assign', ASSIGN_INTROATTACHMENT_FILEAREA, 0);
425                         $fs = get_file_storage();
426                         if ($files = $fs->get_area_files($context->id, 'mod_assign', ASSIGN_INTROATTACHMENT_FILEAREA,
427                                                             0, 'timemodified', false)) {
429                             $assignment['introattachments'] = array();
430                             foreach ($files as $file) {
431                                 $filename = $file->get_filename();
433                                 $assignment['introattachments'][] = array(
434                                     'filename' => $filename,
435                                     'mimetype' => $file->get_mimetype(),
436                                     'fileurl'  => moodle_url::make_webservice_pluginfile_url(
437                                         $context->id, 'mod_assign', ASSIGN_INTROATTACHMENT_FILEAREA, 0, '/', $filename)->out(false)
438                                 );
439                             }
440                         }
441                     }
443                     $assignmentarray[] = $assignment;
444                 }
445             }
446             $coursearray[]= array(
447                 'id' => $courses[$id]->id,
448                 'fullname' => $courses[$id]->fullname,
449                 'shortname' => $courses[$id]->shortname,
450                 'timemodified' => $courses[$id]->timemodified,
451                 'assignments' => $assignmentarray
452             );
453         }
455         $result = array(
456             'courses' => $coursearray,
457             'warnings' => $warnings
458         );
459         return $result;
460     }
462     /**
463      * Creates an assignment external_single_structure
464      *
465      * @return external_single_structure
466      * @since Moodle 2.4
467      */
468     private static function get_assignments_assignment_structure() {
469         return new external_single_structure(
470             array(
471                 'id' => new external_value(PARAM_INT, 'assignment id'),
472                 'cmid' => new external_value(PARAM_INT, 'course module id'),
473                 'course' => new external_value(PARAM_INT, 'course id'),
474                 'name' => new external_value(PARAM_TEXT, 'assignment name'),
475                 'nosubmissions' => new external_value(PARAM_INT, 'no submissions'),
476                 'submissiondrafts' => new external_value(PARAM_INT, 'submissions drafts'),
477                 'sendnotifications' => new external_value(PARAM_INT, 'send notifications'),
478                 'sendlatenotifications' => new external_value(PARAM_INT, 'send notifications'),
479                 'sendstudentnotifications' => new external_value(PARAM_INT, 'send student notifications (default)'),
480                 'duedate' => new external_value(PARAM_INT, 'assignment due date'),
481                 'allowsubmissionsfromdate' => new external_value(PARAM_INT, 'allow submissions from date'),
482                 'grade' => new external_value(PARAM_INT, 'grade type'),
483                 'timemodified' => new external_value(PARAM_INT, 'last time assignment was modified'),
484                 'completionsubmit' => new external_value(PARAM_INT, 'if enabled, set activity as complete following submission'),
485                 'cutoffdate' => new external_value(PARAM_INT, 'date after which submission is not accepted without an extension'),
486                 'teamsubmission' => new external_value(PARAM_INT, 'if enabled, students submit as a team'),
487                 'requireallteammemberssubmit' => new external_value(PARAM_INT, 'if enabled, all team members must submit'),
488                 'teamsubmissiongroupingid' => new external_value(PARAM_INT, 'the grouping id for the team submission groups'),
489                 'blindmarking' => new external_value(PARAM_INT, 'if enabled, hide identities until reveal identities actioned'),
490                 'revealidentities' => new external_value(PARAM_INT, 'show identities for a blind marking assignment'),
491                 'attemptreopenmethod' => new external_value(PARAM_TEXT, 'method used to control opening new attempts'),
492                 'maxattempts' => new external_value(PARAM_INT, 'maximum number of attempts allowed'),
493                 'markingworkflow' => new external_value(PARAM_INT, 'enable marking workflow'),
494                 'markingallocation' => new external_value(PARAM_INT, 'enable marking allocation'),
495                 'requiresubmissionstatement' => new external_value(PARAM_INT, 'student must accept submission statement'),
496                 'configs' => new external_multiple_structure(self::get_assignments_config_structure(), 'configuration settings'),
497                 'intro' => new external_value(PARAM_RAW,
498                     'assignment intro, not allways returned because it deppends on the activity configuration', VALUE_OPTIONAL),
499                 'introformat' => new external_format_value('intro', VALUE_OPTIONAL),
500                 'introattachments' => new external_multiple_structure(
501                     new external_single_structure(
502                         array (
503                             'filename' => new external_value(PARAM_FILE, 'file name'),
504                             'mimetype' => new external_value(PARAM_RAW, 'mime type'),
505                             'fileurl'  => new external_value(PARAM_URL, 'file download url')
506                         )
507                     ), 'intro attachments files', VALUE_OPTIONAL
508                 )
509             ), 'assignment information object');
510     }
512     /**
513      * Creates an assign_plugin_config external_single_structure
514      *
515      * @return external_single_structure
516      * @since Moodle 2.4
517      */
518     private static function get_assignments_config_structure() {
519         return new external_single_structure(
520             array(
521                 'id' => new external_value(PARAM_INT, 'assign_plugin_config id'),
522                 'assignment' => new external_value(PARAM_INT, 'assignment id'),
523                 'plugin' => new external_value(PARAM_TEXT, 'plugin'),
524                 'subtype' => new external_value(PARAM_TEXT, 'subtype'),
525                 'name' => new external_value(PARAM_TEXT, 'name'),
526                 'value' => new external_value(PARAM_TEXT, 'value')
527             ), 'assignment configuration object'
528         );
529     }
531     /**
532      * Creates a course external_single_structure
533      *
534      * @return external_single_structure
535      * @since Moodle 2.4
536      */
537     private static function get_assignments_course_structure() {
538         return new external_single_structure(
539             array(
540                 'id' => new external_value(PARAM_INT, 'course id'),
541                 'fullname' => new external_value(PARAM_TEXT, 'course full name'),
542                 'shortname' => new external_value(PARAM_TEXT, 'course short name'),
543                 'timemodified' => new external_value(PARAM_INT, 'last time modified'),
544                 'assignments' => new external_multiple_structure(self::get_assignments_assignment_structure(), 'assignment info')
545               ), 'course information object'
546         );
547     }
549     /**
550      * Describes the return value for get_assignments
551      *
552      * @return external_single_structure
553      * @since Moodle 2.4
554      */
555     public static function get_assignments_returns() {
556         return new external_single_structure(
557             array(
558                 'courses' => new external_multiple_structure(self::get_assignments_course_structure(), 'list of courses'),
559                 'warnings'  => new external_warnings('item can be \'course\' (errorcode 1 or 2) or \'module\' (errorcode 1)',
560                     'When item is a course then itemid is a course id. When the item is a module then itemid is a module id',
561                     'errorcode can be 1 (no access rights) or 2 (not enrolled or no permissions)')
562             )
563         );
564     }
566     /**
567      * Return information (files and text fields) for the given plugins in the assignment.
568      *
569      * @param  assign $assign the assignment object
570      * @param  array $assignplugins array of assignment plugins (submission or feedback)
571      * @param  stdClass $item the item object (submission or grade)
572      * @return array an array containing the plugins returned information
573      */
574     private static function get_plugins_data($assign, $assignplugins, $item) {
575         global $CFG;
577         $plugins = array();
578         $fs = get_file_storage();
580         foreach ($assignplugins as $assignplugin) {
582             if (!$assignplugin->is_enabled() or !$assignplugin->is_visible()) {
583                 continue;
584             }
586             $plugin = array(
587                 'name' => $assignplugin->get_name(),
588                 'type' => $assignplugin->get_type()
589             );
590             // Subtype is 'assignsubmission', type is currently 'file' or 'onlinetext'.
591             $component = $assignplugin->get_subtype().'_'.$assignplugin->get_type();
593             $fileareas = $assignplugin->get_file_areas();
594             foreach ($fileareas as $filearea => $name) {
595                 $fileareainfo = array('area' => $filearea);
596                 $files = $fs->get_area_files(
597                     $assign->get_context()->id,
598                     $component,
599                     $filearea,
600                     $item->id,
601                     "timemodified",
602                     false
603                 );
604                 foreach ($files as $file) {
605                     $filepath = $file->get_filepath().$file->get_filename();
606                     $fileurl = file_encode_url($CFG->wwwroot . '/webservice/pluginfile.php', '/' . $assign->get_context()->id .
607                         '/' . $component. '/'. $filearea . '/' . $item->id . $filepath);
608                     $fileinfo = array(
609                         'filepath' => $filepath,
610                         'fileurl' => $fileurl
611                         );
612                     $fileareainfo['files'][] = $fileinfo;
613                 }
614                 $plugin['fileareas'][] = $fileareainfo;
615             }
617             $editorfields = $assignplugin->get_editor_fields();
618             foreach ($editorfields as $name => $description) {
619                 $editorfieldinfo = array(
620                     'name' => $name,
621                     'description' => $description,
622                     'text' => $assignplugin->get_editor_text($name, $item->id),
623                     'format' => $assignplugin->get_editor_format($name, $item->id)
624                 );
625                 $plugin['editorfields'][] = $editorfieldinfo;
626             }
627             $plugins[] = $plugin;
628         }
629         return $plugins;
630     }
632     /**
633      * Describes the parameters for get_submissions
634      *
635      * @return external_external_function_parameters
636      * @since Moodle 2.5
637      */
638     public static function get_submissions_parameters() {
639         return new external_function_parameters(
640             array(
641                 'assignmentids' => new external_multiple_structure(
642                     new external_value(PARAM_INT, 'assignment id'),
643                     '1 or more assignment ids',
644                     VALUE_REQUIRED),
645                 'status' => new external_value(PARAM_ALPHA, 'status', VALUE_DEFAULT, ''),
646                 'since' => new external_value(PARAM_INT, 'submitted since', VALUE_DEFAULT, 0),
647                 'before' => new external_value(PARAM_INT, 'submitted before', VALUE_DEFAULT, 0)
648             )
649         );
650     }
652     /**
653      * Returns submissions for the requested assignment ids
654      *
655      * @param int[] $assignmentids
656      * @param string $status only return submissions with this status
657      * @param int $since only return submissions with timemodified >= since
658      * @param int $before only return submissions with timemodified <= before
659      * @return array of submissions for each requested assignment
660      * @since Moodle 2.5
661      */
662     public static function get_submissions($assignmentids, $status = '', $since = 0, $before = 0) {
663         global $DB, $CFG;
665         $params = self::validate_parameters(self::get_submissions_parameters(),
666                         array('assignmentids' => $assignmentids,
667                               'status' => $status,
668                               'since' => $since,
669                               'before' => $before));
671         $warnings = array();
672         $assignments = array();
674         // Check the user is allowed to get the submissions for the assignments requested.
675         $placeholders = array();
676         list($inorequalsql, $placeholders) = $DB->get_in_or_equal($params['assignmentids'], SQL_PARAMS_NAMED);
677         $sql = "SELECT cm.id, cm.instance FROM {course_modules} cm JOIN {modules} md ON md.id = cm.module ".
678                "WHERE md.name = :modname AND cm.instance ".$inorequalsql;
679         $placeholders['modname'] = 'assign';
680         $cms = $DB->get_records_sql($sql, $placeholders);
681         $assigns = array();
682         foreach ($cms as $cm) {
683             try {
684                 $context = context_module::instance($cm->id);
685                 self::validate_context($context);
686                 require_capability('mod/assign:grade', $context);
687                 $assign = new assign($context, null, null);
688                 $assigns[] = $assign;
689             } catch (Exception $e) {
690                 $warnings[] = array(
691                     'item' => 'assignment',
692                     'itemid' => $cm->instance,
693                     'warningcode' => '1',
694                     'message' => 'No access rights in module context'
695                 );
696             }
697         }
699         foreach ($assigns as $assign) {
700             $submissions = array();
701             $placeholders = array('assignid1' => $assign->get_instance()->id,
702                                   'assignid2' => $assign->get_instance()->id);
704             $submissionmaxattempt = 'SELECT mxs.userid, MAX(mxs.attemptnumber) AS maxattempt
705                                      FROM {assign_submission} mxs
706                                      WHERE mxs.assignment = :assignid1 GROUP BY mxs.userid';
708             $sql = "SELECT mas.id, mas.assignment,mas.userid,".
709                    "mas.timecreated,mas.timemodified,mas.status,mas.groupid,mas.attemptnumber ".
710                    "FROM {assign_submission} mas ".
711                    "JOIN ( " . $submissionmaxattempt . " ) smx ON mas.userid = smx.userid ".
712                    "WHERE mas.assignment = :assignid2 AND mas.attemptnumber = smx.maxattempt";
714             if (!empty($params['status'])) {
715                 $placeholders['status'] = $params['status'];
716                 $sql = $sql." AND mas.status = :status";
717             }
718             if (!empty($params['before'])) {
719                 $placeholders['since'] = $params['since'];
720                 $placeholders['before'] = $params['before'];
721                 $sql = $sql." AND mas.timemodified BETWEEN :since AND :before";
722             } else {
723                 $placeholders['since'] = $params['since'];
724                 $sql = $sql." AND mas.timemodified >= :since";
725             }
727             $submissionrecords = $DB->get_records_sql($sql, $placeholders);
729             if (!empty($submissionrecords)) {
730                 $submissionplugins = $assign->get_submission_plugins();
731                 foreach ($submissionrecords as $submissionrecord) {
732                     $submission = array(
733                         'id' => $submissionrecord->id,
734                         'userid' => $submissionrecord->userid,
735                         'timecreated' => $submissionrecord->timecreated,
736                         'timemodified' => $submissionrecord->timemodified,
737                         'status' => $submissionrecord->status,
738                         'attemptnumber' => $submissionrecord->attemptnumber,
739                         'groupid' => $submissionrecord->groupid,
740                         'plugins' => self::get_plugins_data($assign, $submissionplugins, $submissionrecord)
741                     );
742                     $submissions[] = $submission;
743                 }
744             } else {
745                 $warnings[] = array(
746                     'item' => 'module',
747                     'itemid' => $assign->get_instance()->id,
748                     'warningcode' => '3',
749                     'message' => 'No submissions found'
750                 );
751             }
753             $assignments[] = array(
754                 'assignmentid' => $assign->get_instance()->id,
755                 'submissions' => $submissions
756             );
758         }
760         $result = array(
761             'assignments' => $assignments,
762             'warnings' => $warnings
763         );
764         return $result;
765     }
767     /**
768      * Creates an assignment plugin structure.
769      *
770      * @return external_single_structure the plugin structure
771      */
772     private static function get_plugin_structure() {
773         return new external_single_structure(
774             array(
775                 'type' => new external_value(PARAM_TEXT, 'submission plugin type'),
776                 'name' => new external_value(PARAM_TEXT, 'submission plugin name'),
777                 'fileareas' => new external_multiple_structure(
778                     new external_single_structure(
779                         array (
780                             'area' => new external_value (PARAM_TEXT, 'file area'),
781                             'files' => new external_multiple_structure(
782                                 new external_single_structure(
783                                     array (
784                                         'filepath' => new external_value (PARAM_TEXT, 'file path'),
785                                         'fileurl' => new external_value (PARAM_URL, 'file download url',
786                                             VALUE_OPTIONAL)
787                                     )
788                                 ), 'files', VALUE_OPTIONAL
789                             )
790                         )
791                     ), 'fileareas', VALUE_OPTIONAL
792                 ),
793                 'editorfields' => new external_multiple_structure(
794                     new external_single_structure(
795                         array(
796                             'name' => new external_value(PARAM_TEXT, 'field name'),
797                             'description' => new external_value(PARAM_TEXT, 'field description'),
798                             'text' => new external_value (PARAM_RAW, 'field value'),
799                             'format' => new external_format_value ('text')
800                         )
801                     )
802                     , 'editorfields', VALUE_OPTIONAL
803                 )
804             )
805         );
806     }
808     /**
809      * Creates a submission structure.
810      *
811      * @return external_single_structure the submission structure
812      */
813     private static function get_submission_structure($required = VALUE_REQUIRED) {
814         return new external_single_structure(
815             array(
816                 'id' => new external_value(PARAM_INT, 'submission id'),
817                 'userid' => new external_value(PARAM_INT, 'student id'),
818                 'attemptnumber' => new external_value(PARAM_INT, 'attempt number'),
819                 'timecreated' => new external_value(PARAM_INT, 'submission creation time'),
820                 'timemodified' => new external_value(PARAM_INT, 'submission last modified time'),
821                 'status' => new external_value(PARAM_TEXT, 'submission status'),
822                 'groupid' => new external_value(PARAM_INT, 'group id'),
823                 'assignment' => new external_value(PARAM_INT, 'assignment id', VALUE_OPTIONAL),
824                 'latest' => new external_value(PARAM_INT, 'latest attempt', VALUE_OPTIONAL),
825                 'plugins' => new external_multiple_structure(self::get_plugin_structure(), 'plugins', VALUE_OPTIONAL)
826             ), 'submission info', $required
827         );
828     }
830     /**
831      * Creates an assign_submissions external_single_structure
832      *
833      * @return external_single_structure
834      * @since Moodle 2.5
835      */
836     private static function get_submissions_structure() {
837         return new external_single_structure(
838             array (
839                 'assignmentid' => new external_value(PARAM_INT, 'assignment id'),
840                 'submissions' => new external_multiple_structure(self::get_submission_structure())
841             )
842         );
843     }
845     /**
846      * Describes the get_submissions return value
847      *
848      * @return external_single_structure
849      * @since Moodle 2.5
850      */
851     public static function get_submissions_returns() {
852         return new external_single_structure(
853             array(
854                 'assignments' => new external_multiple_structure(self::get_submissions_structure(), 'assignment submissions'),
855                 'warnings' => new external_warnings()
856             )
857         );
858     }
860     /**
861      * Describes the parameters for set_user_flags
862      * @return external_function_parameters
863      * @since  Moodle 2.6
864      */
865     public static function set_user_flags_parameters() {
866         return new external_function_parameters(
867             array(
868                 'assignmentid'    => new external_value(PARAM_INT, 'assignment id'),
869                 'userflags' => new external_multiple_structure(
870                     new external_single_structure(
871                         array(
872                             'userid'           => new external_value(PARAM_INT, 'student id'),
873                             'locked'           => new external_value(PARAM_INT, 'locked', VALUE_OPTIONAL),
874                             'mailed'           => new external_value(PARAM_INT, 'mailed', VALUE_OPTIONAL),
875                             'extensionduedate' => new external_value(PARAM_INT, 'extension due date', VALUE_OPTIONAL),
876                             'workflowstate'    => new external_value(PARAM_TEXT, 'marking workflow state', VALUE_OPTIONAL),
877                             'allocatedmarker'  => new external_value(PARAM_INT, 'allocated marker', VALUE_OPTIONAL)
878                         )
879                     )
880                 )
881             )
882         );
883     }
885     /**
886      * Create or update user_flags records
887      *
888      * @param int $assignmentid the assignment for which the userflags are created or updated
889      * @param array $userflags  An array of userflags to create or update
890      * @return array containing success or failure information for each record
891      * @since Moodle 2.6
892      */
893     public static function set_user_flags($assignmentid, $userflags = array()) {
894         global $CFG, $DB;
896         $params = self::validate_parameters(self::set_user_flags_parameters(),
897                                             array('assignmentid' => $assignmentid,
898                                                   'userflags' => $userflags));
900         // Load assignment if it exists and if the user has the capability.
901         $cm = get_coursemodule_from_instance('assign', $params['assignmentid'], 0, false, MUST_EXIST);
902         $context = context_module::instance($cm->id);
903         self::validate_context($context);
904         require_capability('mod/assign:grade', $context);
905         $assign = new assign($context, null, null);
907         $results = array();
908         foreach ($params['userflags'] as $userflag) {
909             $success = true;
910             $result = array();
912             $record = $assign->get_user_flags($userflag['userid'], false);
913             if ($record) {
914                 if (isset($userflag['locked'])) {
915                     $record->locked = $userflag['locked'];
916                 }
917                 if (isset($userflag['mailed'])) {
918                     $record->mailed = $userflag['mailed'];
919                 }
920                 if (isset($userflag['extensionduedate'])) {
921                     $record->extensionduedate = $userflag['extensionduedate'];
922                 }
923                 if (isset($userflag['workflowstate'])) {
924                     $record->workflowstate = $userflag['workflowstate'];
925                 }
926                 if (isset($userflag['allocatedmarker'])) {
927                     $record->allocatedmarker = $userflag['allocatedmarker'];
928                 }
929                 if ($assign->update_user_flags($record)) {
930                     $result['id'] = $record->id;
931                     $result['userid'] = $userflag['userid'];
932                 } else {
933                     $result['id'] = $record->id;
934                     $result['userid'] = $userflag['userid'];
935                     $result['errormessage'] = 'Record created but values could not be set';
936                 }
937             } else {
938                 $record = $assign->get_user_flags($userflag['userid'], true);
939                 $setfields = isset($userflag['locked'])
940                              || isset($userflag['mailed'])
941                              || isset($userflag['extensionduedate'])
942                              || isset($userflag['workflowstate'])
943                              || isset($userflag['allocatedmarker']);
944                 if ($record) {
945                     if ($setfields) {
946                         if (isset($userflag['locked'])) {
947                             $record->locked = $userflag['locked'];
948                         }
949                         if (isset($userflag['mailed'])) {
950                             $record->mailed = $userflag['mailed'];
951                         }
952                         if (isset($userflag['extensionduedate'])) {
953                             $record->extensionduedate = $userflag['extensionduedate'];
954                         }
955                         if (isset($userflag['workflowstate'])) {
956                             $record->workflowstate = $userflag['workflowstate'];
957                         }
958                         if (isset($userflag['allocatedmarker'])) {
959                             $record->allocatedmarker = $userflag['allocatedmarker'];
960                         }
961                         if ($assign->update_user_flags($record)) {
962                             $result['id'] = $record->id;
963                             $result['userid'] = $userflag['userid'];
964                         } else {
965                             $result['id'] = $record->id;
966                             $result['userid'] = $userflag['userid'];
967                             $result['errormessage'] = 'Record created but values could not be set';
968                         }
969                     } else {
970                         $result['id'] = $record->id;
971                         $result['userid'] = $userflag['userid'];
972                     }
973                 } else {
974                     $result['id'] = -1;
975                     $result['userid'] = $userflag['userid'];
976                     $result['errormessage'] = 'Record could not be created';
977                 }
978             }
980             $results[] = $result;
981         }
982         return $results;
983     }
985     /**
986      * Describes the set_user_flags return value
987      * @return external_multiple_structure
988      * @since  Moodle 2.6
989      */
990     public static function set_user_flags_returns() {
991         return new external_multiple_structure(
992             new external_single_structure(
993                 array(
994                     'id' => new external_value(PARAM_INT, 'id of record if successful, -1 for failure'),
995                     'userid' => new external_value(PARAM_INT, 'userid of record'),
996                     'errormessage' => new external_value(PARAM_TEXT, 'Failure error message', VALUE_OPTIONAL)
997                 )
998             )
999         );
1000     }
1002     /**
1003      * Describes the parameters for get_user_flags
1004      * @return external_function_parameters
1005      * @since  Moodle 2.6
1006      */
1007     public static function get_user_flags_parameters() {
1008         return new external_function_parameters(
1009             array(
1010                 'assignmentids' => new external_multiple_structure(
1011                     new external_value(PARAM_INT, 'assignment id'),
1012                     '1 or more assignment ids',
1013                     VALUE_REQUIRED)
1014             )
1015         );
1016     }
1018     /**
1019      * Returns user flag information from assign_user_flags for the requested assignment ids
1020      * @param int[] $assignmentids
1021      * @return array of user flag records for each requested assignment
1022      * @since  Moodle 2.6
1023      */
1024     public static function get_user_flags($assignmentids) {
1025         global $DB;
1026         $params = self::validate_parameters(self::get_user_flags_parameters(),
1027                         array('assignmentids' => $assignmentids));
1029         $assignments = array();
1030         $warnings = array();
1031         $requestedassignmentids = $params['assignmentids'];
1033         // Check the user is allowed to get the user flags for the assignments requested.
1034         $placeholders = array();
1035         list($sqlassignmentids, $placeholders) = $DB->get_in_or_equal($requestedassignmentids, SQL_PARAMS_NAMED);
1036         $sql = "SELECT cm.id, cm.instance FROM {course_modules} cm JOIN {modules} md ON md.id = cm.module ".
1037                "WHERE md.name = :modname AND cm.instance ".$sqlassignmentids;
1038         $placeholders['modname'] = 'assign';
1039         $cms = $DB->get_records_sql($sql, $placeholders);
1040         foreach ($cms as $cm) {
1041             try {
1042                 $context = context_module::instance($cm->id);
1043                 self::validate_context($context);
1044                 require_capability('mod/assign:grade', $context);
1045             } catch (Exception $e) {
1046                 $requestedassignmentids = array_diff($requestedassignmentids, array($cm->instance));
1047                 $warning = array();
1048                 $warning['item'] = 'assignment';
1049                 $warning['itemid'] = $cm->instance;
1050                 $warning['warningcode'] = '1';
1051                 $warning['message'] = 'No access rights in module context';
1052                 $warnings[] = $warning;
1053             }
1054         }
1056         // Create the query and populate an array of assign_user_flags records from the recordset results.
1057         if (count ($requestedassignmentids) > 0) {
1058             $placeholders = array();
1059             list($inorequalsql, $placeholders) = $DB->get_in_or_equal($requestedassignmentids, SQL_PARAMS_NAMED);
1061             $sql = "SELECT auf.id,auf.assignment,auf.userid,auf.locked,auf.mailed,".
1062                    "auf.extensionduedate,auf.workflowstate,auf.allocatedmarker ".
1063                    "FROM {assign_user_flags} auf ".
1064                    "WHERE auf.assignment ".$inorequalsql.
1065                    " ORDER BY auf.assignment, auf.id";
1067             $rs = $DB->get_recordset_sql($sql, $placeholders);
1068             $currentassignmentid = null;
1069             $assignment = null;
1070             foreach ($rs as $rd) {
1071                 $userflag = array();
1072                 $userflag['id'] = $rd->id;
1073                 $userflag['userid'] = $rd->userid;
1074                 $userflag['locked'] = $rd->locked;
1075                 $userflag['mailed'] = $rd->mailed;
1076                 $userflag['extensionduedate'] = $rd->extensionduedate;
1077                 $userflag['workflowstate'] = $rd->workflowstate;
1078                 $userflag['allocatedmarker'] = $rd->allocatedmarker;
1080                 if (is_null($currentassignmentid) || ($rd->assignment != $currentassignmentid )) {
1081                     if (!is_null($assignment)) {
1082                         $assignments[] = $assignment;
1083                     }
1084                     $assignment = array();
1085                     $assignment['assignmentid'] = $rd->assignment;
1086                     $assignment['userflags'] = array();
1087                     $requestedassignmentids = array_diff($requestedassignmentids, array($rd->assignment));
1088                 }
1089                 $assignment['userflags'][] = $userflag;
1091                 $currentassignmentid = $rd->assignment;
1092             }
1093             if (!is_null($assignment)) {
1094                 $assignments[] = $assignment;
1095             }
1096             $rs->close();
1098         }
1100         foreach ($requestedassignmentids as $assignmentid) {
1101             $warning = array();
1102             $warning['item'] = 'assignment';
1103             $warning['itemid'] = $assignmentid;
1104             $warning['warningcode'] = '3';
1105             $warning['message'] = 'No user flags found';
1106             $warnings[] = $warning;
1107         }
1109         $result = array();
1110         $result['assignments'] = $assignments;
1111         $result['warnings'] = $warnings;
1112         return $result;
1113     }
1115     /**
1116      * Creates an assign_user_flags external_single_structure
1117      * @return external_single_structure
1118      * @since  Moodle 2.6
1119      */
1120     private static function assign_user_flags() {
1121         return new external_single_structure(
1122             array (
1123                 'assignmentid'    => new external_value(PARAM_INT, 'assignment id'),
1124                 'userflags'   => new external_multiple_structure(new external_single_structure(
1125                         array(
1126                             'id'               => new external_value(PARAM_INT, 'user flag id'),
1127                             'userid'           => new external_value(PARAM_INT, 'student id'),
1128                             'locked'           => new external_value(PARAM_INT, 'locked'),
1129                             'mailed'           => new external_value(PARAM_INT, 'mailed'),
1130                             'extensionduedate' => new external_value(PARAM_INT, 'extension due date'),
1131                             'workflowstate'    => new external_value(PARAM_TEXT, 'marking workflow state', VALUE_OPTIONAL),
1132                             'allocatedmarker'  => new external_value(PARAM_INT, 'allocated marker')
1133                         )
1134                     )
1135                 )
1136             )
1137         );
1138     }
1140     /**
1141      * Describes the get_user_flags return value
1142      * @return external_single_structure
1143      * @since  Moodle 2.6
1144      */
1145     public static function get_user_flags_returns() {
1146         return new external_single_structure(
1147             array(
1148                 'assignments' => new external_multiple_structure(self::assign_user_flags(), 'list of assign user flag information'),
1149                 'warnings'      => new external_warnings('item is always \'assignment\'',
1150                     'when errorcode is 3 then itemid is an assignment id. When errorcode is 1, itemid is a course module id',
1151                     'errorcode can be 3 (no user flags found) or 1 (no permission to get user flags)')
1152             )
1153         );
1154     }
1156     /**
1157      * Describes the parameters for get_user_mappings
1158      * @return external_function_parameters
1159      * @since  Moodle 2.6
1160      */
1161     public static function get_user_mappings_parameters() {
1162         return new external_function_parameters(
1163             array(
1164                 'assignmentids' => new external_multiple_structure(
1165                     new external_value(PARAM_INT, 'assignment id'),
1166                     '1 or more assignment ids',
1167                     VALUE_REQUIRED)
1168             )
1169         );
1170     }
1172     /**
1173      * Returns user mapping information from assign_user_mapping for the requested assignment ids
1174      * @param int[] $assignmentids
1175      * @return array of user mapping records for each requested assignment
1176      * @since  Moodle 2.6
1177      */
1178     public static function get_user_mappings($assignmentids) {
1179         global $DB;
1180         $params = self::validate_parameters(self::get_user_mappings_parameters(),
1181                         array('assignmentids' => $assignmentids));
1183         $assignments = array();
1184         $warnings = array();
1185         $requestedassignmentids = $params['assignmentids'];
1187         // Check the user is allowed to get the mappings for the assignments requested.
1188         $placeholders = array();
1189         list($sqlassignmentids, $placeholders) = $DB->get_in_or_equal($requestedassignmentids, SQL_PARAMS_NAMED);
1190         $sql = "SELECT cm.id, cm.instance FROM {course_modules} cm JOIN {modules} md ON md.id = cm.module ".
1191                "WHERE md.name = :modname AND cm.instance ".$sqlassignmentids;
1192         $placeholders['modname'] = 'assign';
1193         $cms = $DB->get_records_sql($sql, $placeholders);
1194         foreach ($cms as $cm) {
1195             try {
1196                 $context = context_module::instance($cm->id);
1197                 self::validate_context($context);
1198                 require_capability('mod/assign:revealidentities', $context);
1199             } catch (Exception $e) {
1200                 $requestedassignmentids = array_diff($requestedassignmentids, array($cm->instance));
1201                 $warning = array();
1202                 $warning['item'] = 'assignment';
1203                 $warning['itemid'] = $cm->instance;
1204                 $warning['warningcode'] = '1';
1205                 $warning['message'] = 'No access rights in module context';
1206                 $warnings[] = $warning;
1207             }
1208         }
1210         // Create the query and populate an array of assign_user_mapping records from the recordset results.
1211         if (count ($requestedassignmentids) > 0) {
1212             $placeholders = array();
1213             list($inorequalsql, $placeholders) = $DB->get_in_or_equal($requestedassignmentids, SQL_PARAMS_NAMED);
1215             $sql = "SELECT aum.id,aum.assignment,aum.userid ".
1216                    "FROM {assign_user_mapping} aum ".
1217                    "WHERE aum.assignment ".$inorequalsql.
1218                    " ORDER BY aum.assignment, aum.id";
1220             $rs = $DB->get_recordset_sql($sql, $placeholders);
1221             $currentassignmentid = null;
1222             $assignment = null;
1223             foreach ($rs as $rd) {
1224                 $mapping = array();
1225                 $mapping['id'] = $rd->id;
1226                 $mapping['userid'] = $rd->userid;
1228                 if (is_null($currentassignmentid) || ($rd->assignment != $currentassignmentid )) {
1229                     if (!is_null($assignment)) {
1230                         $assignments[] = $assignment;
1231                     }
1232                     $assignment = array();
1233                     $assignment['assignmentid'] = $rd->assignment;
1234                     $assignment['mappings'] = array();
1235                     $requestedassignmentids = array_diff($requestedassignmentids, array($rd->assignment));
1236                 }
1237                 $assignment['mappings'][] = $mapping;
1239                 $currentassignmentid = $rd->assignment;
1240             }
1241             if (!is_null($assignment)) {
1242                 $assignments[] = $assignment;
1243             }
1244             $rs->close();
1246         }
1248         foreach ($requestedassignmentids as $assignmentid) {
1249             $warning = array();
1250             $warning['item'] = 'assignment';
1251             $warning['itemid'] = $assignmentid;
1252             $warning['warningcode'] = '3';
1253             $warning['message'] = 'No mappings found';
1254             $warnings[] = $warning;
1255         }
1257         $result = array();
1258         $result['assignments'] = $assignments;
1259         $result['warnings'] = $warnings;
1260         return $result;
1261     }
1263     /**
1264      * Creates an assign_user_mappings external_single_structure
1265      * @return external_single_structure
1266      * @since  Moodle 2.6
1267      */
1268     private static function assign_user_mappings() {
1269         return new external_single_structure(
1270             array (
1271                 'assignmentid'    => new external_value(PARAM_INT, 'assignment id'),
1272                 'mappings'   => new external_multiple_structure(new external_single_structure(
1273                         array(
1274                             'id'     => new external_value(PARAM_INT, 'user mapping id'),
1275                             'userid' => new external_value(PARAM_INT, 'student id')
1276                         )
1277                     )
1278                 )
1279             )
1280         );
1281     }
1283     /**
1284      * Describes the get_user_mappings return value
1285      * @return external_single_structure
1286      * @since  Moodle 2.6
1287      */
1288     public static function get_user_mappings_returns() {
1289         return new external_single_structure(
1290             array(
1291                 'assignments' => new external_multiple_structure(self::assign_user_mappings(), 'list of assign user mapping data'),
1292                 'warnings'      => new external_warnings('item is always \'assignment\'',
1293                     'when errorcode is 3 then itemid is an assignment id. When errorcode is 1, itemid is a course module id',
1294                     'errorcode can be 3 (no user mappings found) or 1 (no permission to get user mappings)')
1295             )
1296         );
1297     }
1299     /**
1300      * Describes the parameters for lock_submissions
1301      * @return external_external_function_parameters
1302      * @since  Moodle 2.6
1303      */
1304     public static function lock_submissions_parameters() {
1305         return new external_function_parameters(
1306             array(
1307                 'assignmentid' => new external_value(PARAM_INT, 'The assignment id to operate on'),
1308                 'userids' => new external_multiple_structure(
1309                     new external_value(PARAM_INT, 'user id'),
1310                     '1 or more user ids',
1311                     VALUE_REQUIRED),
1312             )
1313         );
1314     }
1316     /**
1317      * Locks (prevent updates to) submissions in this assignment.
1318      *
1319      * @param int $assignmentid The id of the assignment
1320      * @param array $userids Array of user ids to lock
1321      * @return array of warnings for each submission that could not be locked.
1322      * @since Moodle 2.6
1323      */
1324     public static function lock_submissions($assignmentid, $userids) {
1325         global $CFG;
1327         $params = self::validate_parameters(self::lock_submissions_parameters(),
1328                         array('assignmentid' => $assignmentid,
1329                               'userids' => $userids));
1331         $cm = get_coursemodule_from_instance('assign', $params['assignmentid'], 0, false, MUST_EXIST);
1332         $context = context_module::instance($cm->id);
1333         self::validate_context($context);
1335         $assignment = new assign($context, $cm, null);
1337         $warnings = array();
1338         foreach ($params['userids'] as $userid) {
1339             if (!$assignment->lock_submission($userid)) {
1340                 $detail = 'User id: ' . $userid . ', Assignment id: ' . $params['assignmentid'];
1341                 $warnings[] = self::generate_warning($params['assignmentid'],
1342                                                      'couldnotlock',
1343                                                      $detail);
1344             }
1345         }
1347         return $warnings;
1348     }
1350     /**
1351      * Describes the return value for lock_submissions
1352      *
1353      * @return external_single_structure
1354      * @since Moodle 2.6
1355      */
1356     public static function lock_submissions_returns() {
1357         return new external_warnings();
1358     }
1360     /**
1361      * Describes the parameters for revert_submissions_to_draft
1362      * @return external_external_function_parameters
1363      * @since  Moodle 2.6
1364      */
1365     public static function revert_submissions_to_draft_parameters() {
1366         return new external_function_parameters(
1367             array(
1368                 'assignmentid' => new external_value(PARAM_INT, 'The assignment id to operate on'),
1369                 'userids' => new external_multiple_structure(
1370                     new external_value(PARAM_INT, 'user id'),
1371                     '1 or more user ids',
1372                     VALUE_REQUIRED),
1373             )
1374         );
1375     }
1377     /**
1378      * Reverts a list of user submissions to draft for a single assignment.
1379      *
1380      * @param int $assignmentid The id of the assignment
1381      * @param array $userids Array of user ids to revert
1382      * @return array of warnings for each submission that could not be reverted.
1383      * @since Moodle 2.6
1384      */
1385     public static function revert_submissions_to_draft($assignmentid, $userids) {
1386         global $CFG;
1388         $params = self::validate_parameters(self::revert_submissions_to_draft_parameters(),
1389                         array('assignmentid' => $assignmentid,
1390                               'userids' => $userids));
1392         $cm = get_coursemodule_from_instance('assign', $params['assignmentid'], 0, false, MUST_EXIST);
1393         $context = context_module::instance($cm->id);
1394         self::validate_context($context);
1396         $assignment = new assign($context, $cm, null);
1398         $warnings = array();
1399         foreach ($params['userids'] as $userid) {
1400             if (!$assignment->revert_to_draft($userid)) {
1401                 $detail = 'User id: ' . $userid . ', Assignment id: ' . $params['assignmentid'];
1402                 $warnings[] = self::generate_warning($params['assignmentid'],
1403                                                      'couldnotrevert',
1404                                                      $detail);
1405             }
1406         }
1408         return $warnings;
1409     }
1411     /**
1412      * Describes the return value for revert_submissions_to_draft
1413      *
1414      * @return external_single_structure
1415      * @since Moodle 2.6
1416      */
1417     public static function revert_submissions_to_draft_returns() {
1418         return new external_warnings();
1419     }
1421     /**
1422      * Describes the parameters for unlock_submissions
1423      * @return external_external_function_parameters
1424      * @since  Moodle 2.6
1425      */
1426     public static function unlock_submissions_parameters() {
1427         return new external_function_parameters(
1428             array(
1429                 'assignmentid' => new external_value(PARAM_INT, 'The assignment id to operate on'),
1430                 'userids' => new external_multiple_structure(
1431                     new external_value(PARAM_INT, 'user id'),
1432                     '1 or more user ids',
1433                     VALUE_REQUIRED),
1434             )
1435         );
1436     }
1438     /**
1439      * Locks (prevent updates to) submissions in this assignment.
1440      *
1441      * @param int $assignmentid The id of the assignment
1442      * @param array $userids Array of user ids to lock
1443      * @return array of warnings for each submission that could not be locked.
1444      * @since Moodle 2.6
1445      */
1446     public static function unlock_submissions($assignmentid, $userids) {
1447         global $CFG;
1449         $params = self::validate_parameters(self::unlock_submissions_parameters(),
1450                         array('assignmentid' => $assignmentid,
1451                               'userids' => $userids));
1453         $cm = get_coursemodule_from_instance('assign', $params['assignmentid'], 0, false, MUST_EXIST);
1454         $context = context_module::instance($cm->id);
1455         self::validate_context($context);
1457         $assignment = new assign($context, $cm, null);
1459         $warnings = array();
1460         foreach ($params['userids'] as $userid) {
1461             if (!$assignment->unlock_submission($userid)) {
1462                 $detail = 'User id: ' . $userid . ', Assignment id: ' . $params['assignmentid'];
1463                 $warnings[] = self::generate_warning($params['assignmentid'],
1464                                                      'couldnotunlock',
1465                                                      $detail);
1466             }
1467         }
1469         return $warnings;
1470     }
1472     /**
1473      * Describes the return value for unlock_submissions
1474      *
1475      * @return external_single_structure
1476      * @since Moodle 2.6
1477      */
1478     public static function unlock_submissions_returns() {
1479         return new external_warnings();
1480     }
1482     /**
1483      * Describes the parameters for submit_for_grading
1484      * @return external_external_function_parameters
1485      * @since  Moodle 2.6
1486      */
1487     public static function submit_for_grading_parameters() {
1488         return new external_function_parameters(
1489             array(
1490                 'assignmentid' => new external_value(PARAM_INT, 'The assignment id to operate on'),
1491                 'acceptsubmissionstatement' => new external_value(PARAM_BOOL, 'Accept the assignment submission statement')
1492             )
1493         );
1494     }
1496     /**
1497      * Submit the logged in users assignment for grading.
1498      *
1499      * @param int $assignmentid The id of the assignment
1500      * @return array of warnings to indicate any errors.
1501      * @since Moodle 2.6
1502      */
1503     public static function submit_for_grading($assignmentid, $acceptsubmissionstatement) {
1504         global $CFG, $USER;
1506         $params = self::validate_parameters(self::submit_for_grading_parameters(),
1507                                             array('assignmentid' => $assignmentid,
1508                                                   'acceptsubmissionstatement' => $acceptsubmissionstatement));
1510         $cm = get_coursemodule_from_instance('assign', $params['assignmentid'], 0, false, MUST_EXIST);
1511         $context = context_module::instance($cm->id);
1512         self::validate_context($context);
1514         $assignment = new assign($context, $cm, null);
1516         $warnings = array();
1517         $data = new stdClass();
1518         $data->submissionstatement = $params['acceptsubmissionstatement'];
1519         $notices = array();
1521         if (!$assignment->submit_for_grading($data, $notices)) {
1522             $detail = 'User id: ' . $USER->id . ', Assignment id: ' . $params['assignmentid'] . ' Notices:' . implode(', ', $notices);
1523             $warnings[] = self::generate_warning($params['assignmentid'],
1524                                                  'couldnotsubmitforgrading',
1525                                                  $detail);
1526         }
1528         return $warnings;
1529     }
1531     /**
1532      * Describes the return value for submit_for_grading
1533      *
1534      * @return external_single_structure
1535      * @since Moodle 2.6
1536      */
1537     public static function submit_for_grading_returns() {
1538         return new external_warnings();
1539     }
1541     /**
1542      * Describes the parameters for save_user_extensions
1543      * @return external_external_function_parameters
1544      * @since  Moodle 2.6
1545      */
1546     public static function save_user_extensions_parameters() {
1547         return new external_function_parameters(
1548             array(
1549                 'assignmentid' => new external_value(PARAM_INT, 'The assignment id to operate on'),
1550                 'userids' => new external_multiple_structure(
1551                     new external_value(PARAM_INT, 'user id'),
1552                     '1 or more user ids',
1553                     VALUE_REQUIRED),
1554                 'dates' => new external_multiple_structure(
1555                     new external_value(PARAM_INT, 'dates'),
1556                     '1 or more extension dates (timestamp)',
1557                     VALUE_REQUIRED),
1558             )
1559         );
1560     }
1562     /**
1563      * Grant extension dates to students for an assignment.
1564      *
1565      * @param int $assignmentid The id of the assignment
1566      * @param array $userids Array of user ids to grant extensions to
1567      * @param array $dates Array of extension dates
1568      * @return array of warnings for each extension date that could not be granted
1569      * @since Moodle 2.6
1570      */
1571     public static function save_user_extensions($assignmentid, $userids, $dates) {
1572         global $CFG;
1574         $params = self::validate_parameters(self::save_user_extensions_parameters(),
1575                         array('assignmentid' => $assignmentid,
1576                               'userids' => $userids,
1577                               'dates' => $dates));
1579         if (count($params['userids']) != count($params['dates'])) {
1580             $detail = 'Length of userids and dates parameters differ.';
1581             $warnings[] = self::generate_warning($params['assignmentid'],
1582                                                  'invalidparameters',
1583                                                  $detail);
1585             return $warnings;
1586         }
1588         $cm = get_coursemodule_from_instance('assign', $params['assignmentid'], 0, false, MUST_EXIST);
1589         $context = context_module::instance($cm->id);
1590         self::validate_context($context);
1592         $assignment = new assign($context, $cm, null);
1594         $warnings = array();
1595         foreach ($params['userids'] as $idx => $userid) {
1596             $duedate = $params['dates'][$idx];
1597             if (!$assignment->save_user_extension($userid, $duedate)) {
1598                 $detail = 'User id: ' . $userid . ', Assignment id: ' . $params['assignmentid'] . ', Extension date: ' . $duedate;
1599                 $warnings[] = self::generate_warning($params['assignmentid'],
1600                                                      'couldnotgrantextensions',
1601                                                      $detail);
1602             }
1603         }
1605         return $warnings;
1606     }
1608     /**
1609      * Describes the return value for save_user_extensions
1610      *
1611      * @return external_single_structure
1612      * @since Moodle 2.6
1613      */
1614     public static function save_user_extensions_returns() {
1615         return new external_warnings();
1616     }
1618     /**
1619      * Describes the parameters for reveal_identities
1620      * @return external_external_function_parameters
1621      * @since  Moodle 2.6
1622      */
1623     public static function reveal_identities_parameters() {
1624         return new external_function_parameters(
1625             array(
1626                 'assignmentid' => new external_value(PARAM_INT, 'The assignment id to operate on')
1627             )
1628         );
1629     }
1631     /**
1632      * Reveal the identities of anonymous students to markers for a single assignment.
1633      *
1634      * @param int $assignmentid The id of the assignment
1635      * @return array of warnings to indicate any errors.
1636      * @since Moodle 2.6
1637      */
1638     public static function reveal_identities($assignmentid) {
1639         global $CFG, $USER;
1641         $params = self::validate_parameters(self::reveal_identities_parameters(),
1642                                             array('assignmentid' => $assignmentid));
1644         $cm = get_coursemodule_from_instance('assign', $params['assignmentid'], 0, false, MUST_EXIST);
1645         $context = context_module::instance($cm->id);
1646         self::validate_context($context);
1648         $assignment = new assign($context, $cm, null);
1650         $warnings = array();
1651         if (!$assignment->reveal_identities()) {
1652             $detail = 'User id: ' . $USER->id . ', Assignment id: ' . $params['assignmentid'];
1653             $warnings[] = self::generate_warning($params['assignmentid'],
1654                                                  'couldnotrevealidentities',
1655                                                  $detail);
1656         }
1658         return $warnings;
1659     }
1661     /**
1662      * Describes the return value for reveal_identities
1663      *
1664      * @return external_single_structure
1665      * @since Moodle 2.6
1666      */
1667     public static function reveal_identities_returns() {
1668         return new external_warnings();
1669     }
1671     /**
1672      * Describes the parameters for save_submission
1673      * @return external_external_function_parameters
1674      * @since  Moodle 2.6
1675      */
1676     public static function save_submission_parameters() {
1677         global $CFG;
1678         $instance = new assign(null, null, null);
1679         $pluginsubmissionparams = array();
1681         foreach ($instance->get_submission_plugins() as $plugin) {
1682             if ($plugin->is_visible()) {
1683                 $pluginparams = $plugin->get_external_parameters();
1684                 if (!empty($pluginparams)) {
1685                     $pluginsubmissionparams = array_merge($pluginsubmissionparams, $pluginparams);
1686                 }
1687             }
1688         }
1690         return new external_function_parameters(
1691             array(
1692                 'assignmentid' => new external_value(PARAM_INT, 'The assignment id to operate on'),
1693                 'plugindata' => new external_single_structure(
1694                     $pluginsubmissionparams
1695                 )
1696             )
1697         );
1698     }
1700     /**
1701      * Save a student submission for a single assignment
1702      *
1703      * @param int $assignmentid The id of the assignment
1704      * @param array $plugindata - The submitted data for plugins
1705      * @return array of warnings to indicate any errors
1706      * @since Moodle 2.6
1707      */
1708     public static function save_submission($assignmentid, $plugindata) {
1709         global $CFG, $USER;
1711         $params = self::validate_parameters(self::save_submission_parameters(),
1712                                             array('assignmentid' => $assignmentid,
1713                                                   'plugindata' => $plugindata));
1715         $cm = get_coursemodule_from_instance('assign', $params['assignmentid'], 0, false, MUST_EXIST);
1716         $context = context_module::instance($cm->id);
1717         self::validate_context($context);
1719         $assignment = new assign($context, $cm, null);
1721         $notices = array();
1723         if (!$assignment->submissions_open($USER->id)) {
1724             $notices[] = get_string('duedatereached', 'assign');
1725         } else {
1726             $submissiondata = (object)$params['plugindata'];
1727             $assignment->save_submission($submissiondata, $notices);
1728         }
1730         $warnings = array();
1731         foreach ($notices as $notice) {
1732             $warnings[] = self::generate_warning($params['assignmentid'],
1733                                                  'couldnotsavesubmission',
1734                                                  $notice);
1735         }
1737         return $warnings;
1738     }
1740     /**
1741      * Describes the return value for save_submission
1742      *
1743      * @return external_single_structure
1744      * @since Moodle 2.6
1745      */
1746     public static function save_submission_returns() {
1747         return new external_warnings();
1748     }
1750     /**
1751      * Describes the parameters for save_grade
1752      * @return external_external_function_parameters
1753      * @since  Moodle 2.6
1754      */
1755     public static function save_grade_parameters() {
1756         global $CFG;
1757         require_once("$CFG->dirroot/grade/grading/lib.php");
1758         $instance = new assign(null, null, null);
1759         $pluginfeedbackparams = array();
1761         foreach ($instance->get_feedback_plugins() as $plugin) {
1762             if ($plugin->is_visible()) {
1763                 $pluginparams = $plugin->get_external_parameters();
1764                 if (!empty($pluginparams)) {
1765                     $pluginfeedbackparams = array_merge($pluginfeedbackparams, $pluginparams);
1766                 }
1767             }
1768         }
1770         $advancedgradingdata = array();
1771         $methods = array_keys(grading_manager::available_methods(false));
1772         foreach ($methods as $method) {
1773             require_once($CFG->dirroot.'/grade/grading/form/'.$method.'/lib.php');
1774             $details  = call_user_func('gradingform_'.$method.'_controller::get_external_instance_filling_details');
1775             if (!empty($details)) {
1776                 $items = array();
1777                 foreach ($details as $key => $value) {
1778                     $value->required = VALUE_OPTIONAL;
1779                     unset($value->content->keys['id']);
1780                     $items[$key] = new external_multiple_structure (new external_single_structure(
1781                         array(
1782                             'criterionid' => new external_value(PARAM_INT, 'criterion id'),
1783                             'fillings' => $value
1784                         )
1785                     ));
1786                 }
1787                 $advancedgradingdata[$method] = new external_single_structure($items, 'items', VALUE_OPTIONAL);
1788             }
1789         }
1791         return new external_function_parameters(
1792             array(
1793                 'assignmentid' => new external_value(PARAM_INT, 'The assignment id to operate on'),
1794                 'userid' => new external_value(PARAM_INT, 'The student id to operate on'),
1795                 'grade' => new external_value(PARAM_FLOAT, 'The new grade for this user. Ignored if advanced grading used'),
1796                 'attemptnumber' => new external_value(PARAM_INT, 'The attempt number (-1 means latest attempt)'),
1797                 'addattempt' => new external_value(PARAM_BOOL, 'Allow another attempt if the attempt reopen method is manual'),
1798                 'workflowstate' => new external_value(PARAM_ALPHA, 'The next marking workflow state'),
1799                 'applytoall' => new external_value(PARAM_BOOL, 'If true, this grade will be applied ' .
1800                                                                'to all members ' .
1801                                                                'of the group (for group assignments).'),
1802                 'plugindata' => new external_single_structure($pluginfeedbackparams, 'plugin data', VALUE_DEFAULT, array()),
1803                 'advancedgradingdata' => new external_single_structure($advancedgradingdata, 'advanced grading data',
1804                                                                        VALUE_DEFAULT, array())
1805             )
1806         );
1807     }
1809     /**
1810      * Save a student grade for a single assignment.
1811      *
1812      * @param int $assignmentid The id of the assignment
1813      * @param int $userid The id of the user
1814      * @param float $grade The grade (ignored if the assignment uses advanced grading)
1815      * @param int $attemptnumber The attempt number
1816      * @param bool $addattempt Allow another attempt
1817      * @param string $workflowstate New workflow state
1818      * @param bool $applytoall Apply the grade to all members of the group
1819      * @param array $plugindata Custom data used by plugins
1820      * @param array $advancedgradingdata Advanced grading data
1821      * @return null
1822      * @since Moodle 2.6
1823      */
1824     public static function save_grade($assignmentid,
1825                                       $userid,
1826                                       $grade,
1827                                       $attemptnumber,
1828                                       $addattempt,
1829                                       $workflowstate,
1830                                       $applytoall,
1831                                       $plugindata = array(),
1832                                       $advancedgradingdata = array()) {
1833         global $CFG, $USER;
1835         $params = self::validate_parameters(self::save_grade_parameters(),
1836                                             array('assignmentid' => $assignmentid,
1837                                                   'userid' => $userid,
1838                                                   'grade' => $grade,
1839                                                   'attemptnumber' => $attemptnumber,
1840                                                   'workflowstate' => $workflowstate,
1841                                                   'addattempt' => $addattempt,
1842                                                   'applytoall' => $applytoall,
1843                                                   'plugindata' => $plugindata,
1844                                                   'advancedgradingdata' => $advancedgradingdata));
1846         $cm = get_coursemodule_from_instance('assign', $params['assignmentid'], 0, false, MUST_EXIST);
1847         $context = context_module::instance($cm->id);
1848         self::validate_context($context);
1850         $assignment = new assign($context, $cm, null);
1852         $gradedata = (object)$params['plugindata'];
1854         $gradedata->addattempt = $params['addattempt'];
1855         $gradedata->attemptnumber = $params['attemptnumber'];
1856         $gradedata->workflowstate = $params['workflowstate'];
1857         $gradedata->applytoall = $params['applytoall'];
1858         $gradedata->grade = $params['grade'];
1860         if (!empty($params['advancedgradingdata'])) {
1861             $advancedgrading = array();
1862             $criteria = reset($params['advancedgradingdata']);
1863             foreach ($criteria as $key => $criterion) {
1864                 $details = array();
1865                 foreach ($criterion as $value) {
1866                     foreach ($value['fillings'] as $filling) {
1867                         $details[$value['criterionid']] = $filling;
1868                     }
1869                 }
1870                 $advancedgrading[$key] = $details;
1871             }
1872             $gradedata->advancedgrading = $advancedgrading;
1873         }
1875         $assignment->save_grade($params['userid'], $gradedata);
1877         return null;
1878     }
1880     /**
1881      * Describes the return value for save_grade
1882      *
1883      * @return external_single_structure
1884      * @since Moodle 2.6
1885      */
1886     public static function save_grade_returns() {
1887         return null;
1888     }
1890     /**
1891      * Describes the parameters for save_grades
1892      * @return external_external_function_parameters
1893      * @since  Moodle 2.7
1894      */
1895     public static function save_grades_parameters() {
1896         global $CFG;
1897         require_once("$CFG->dirroot/grade/grading/lib.php");
1898         $instance = new assign(null, null, null);
1899         $pluginfeedbackparams = array();
1901         foreach ($instance->get_feedback_plugins() as $plugin) {
1902             if ($plugin->is_visible()) {
1903                 $pluginparams = $plugin->get_external_parameters();
1904                 if (!empty($pluginparams)) {
1905                     $pluginfeedbackparams = array_merge($pluginfeedbackparams, $pluginparams);
1906                 }
1907             }
1908         }
1910         $advancedgradingdata = array();
1911         $methods = array_keys(grading_manager::available_methods(false));
1912         foreach ($methods as $method) {
1913             require_once($CFG->dirroot.'/grade/grading/form/'.$method.'/lib.php');
1914             $details  = call_user_func('gradingform_'.$method.'_controller::get_external_instance_filling_details');
1915             if (!empty($details)) {
1916                 $items = array();
1917                 foreach ($details as $key => $value) {
1918                     $value->required = VALUE_OPTIONAL;
1919                     unset($value->content->keys['id']);
1920                     $items[$key] = new external_multiple_structure (new external_single_structure(
1921                         array(
1922                             'criterionid' => new external_value(PARAM_INT, 'criterion id'),
1923                             'fillings' => $value
1924                         )
1925                     ));
1926                 }
1927                 $advancedgradingdata[$method] = new external_single_structure($items, 'items', VALUE_OPTIONAL);
1928             }
1929         }
1931         return new external_function_parameters(
1932             array(
1933                 'assignmentid' => new external_value(PARAM_INT, 'The assignment id to operate on'),
1934                 'applytoall' => new external_value(PARAM_BOOL, 'If true, this grade will be applied ' .
1935                                                                'to all members ' .
1936                                                                'of the group (for group assignments).'),
1937                 'grades' => new external_multiple_structure(
1938                     new external_single_structure(
1939                         array (
1940                             'userid' => new external_value(PARAM_INT, 'The student id to operate on'),
1941                             'grade' => new external_value(PARAM_FLOAT, 'The new grade for this user. '.
1942                                                                        'Ignored if advanced grading used'),
1943                             'attemptnumber' => new external_value(PARAM_INT, 'The attempt number (-1 means latest attempt)'),
1944                             'addattempt' => new external_value(PARAM_BOOL, 'Allow another attempt if manual attempt reopen method'),
1945                             'workflowstate' => new external_value(PARAM_ALPHA, 'The next marking workflow state'),
1946                             'plugindata' => new external_single_structure($pluginfeedbackparams, 'plugin data',
1947                                                                           VALUE_DEFAULT, array()),
1948                             'advancedgradingdata' => new external_single_structure($advancedgradingdata, 'advanced grading data',
1949                                                                                    VALUE_DEFAULT, array())
1950                         )
1951                     )
1952                 )
1953             )
1954         );
1955     }
1957     /**
1958      * Save multiple student grades for a single assignment.
1959      *
1960      * @param int $assignmentid The id of the assignment
1961      * @param boolean $applytoall If set to true and this is a team assignment,
1962      * apply the grade to all members of the group
1963      * @param array $grades grade data for one or more students that includes
1964      *                  userid - The id of the student being graded
1965      *                  grade - The grade (ignored if the assignment uses advanced grading)
1966      *                  attemptnumber - The attempt number
1967      *                  addattempt - Allow another attempt
1968      *                  workflowstate - New workflow state
1969      *                  plugindata - Custom data used by plugins
1970      *                  advancedgradingdata - Optional Advanced grading data
1971      * @throws invalid_parameter_exception if multiple grades are supplied for
1972      * a team assignment that has $applytoall set to true
1973      * @return null
1974      * @since Moodle 2.7
1975      */
1976     public static function save_grades($assignmentid, $applytoall = false, $grades) {
1977         global $CFG, $USER;
1979         $params = self::validate_parameters(self::save_grades_parameters(),
1980                                             array('assignmentid' => $assignmentid,
1981                                                   'applytoall' => $applytoall,
1982                                                   'grades' => $grades));
1984         $cm = get_coursemodule_from_instance('assign', $params['assignmentid'], 0, false, MUST_EXIST);
1985         $context = context_module::instance($cm->id);
1986         self::validate_context($context);
1987         $assignment = new assign($context, $cm, null);
1989         if ($assignment->get_instance()->teamsubmission && $params['applytoall']) {
1990             // Check that only 1 user per submission group is provided.
1991             $groupids = array();
1992             foreach ($params['grades'] as $gradeinfo) {
1993                 $group = $assignment->get_submission_group($gradeinfo['userid']);
1994                 if (in_array($group->id, $groupids)) {
1995                     throw new invalid_parameter_exception('Multiple grades for the same team have been supplied '
1996                                                           .' this is not permitted when the applytoall flag is set');
1997                 } else {
1998                     $groupids[] = $group->id;
1999                 }
2000             }
2001         }
2003         foreach ($params['grades'] as $gradeinfo) {
2004             $gradedata = (object)$gradeinfo['plugindata'];
2005             $gradedata->addattempt = $gradeinfo['addattempt'];
2006             $gradedata->attemptnumber = $gradeinfo['attemptnumber'];
2007             $gradedata->workflowstate = $gradeinfo['workflowstate'];
2008             $gradedata->applytoall = $params['applytoall'];
2009             $gradedata->grade = $gradeinfo['grade'];
2011             if (!empty($gradeinfo['advancedgradingdata'])) {
2012                 $advancedgrading = array();
2013                 $criteria = reset($gradeinfo['advancedgradingdata']);
2014                 foreach ($criteria as $key => $criterion) {
2015                     $details = array();
2016                     foreach ($criterion as $value) {
2017                         foreach ($value['fillings'] as $filling) {
2018                             $details[$value['criterionid']] = $filling;
2019                         }
2020                     }
2021                     $advancedgrading[$key] = $details;
2022                 }
2023                 $gradedata->advancedgrading = $advancedgrading;
2024             }
2025             $assignment->save_grade($gradeinfo['userid'], $gradedata);
2026         }
2028         return null;
2029     }
2031     /**
2032      * Describes the return value for save_grades
2033      *
2034      * @return external_single_structure
2035      * @since Moodle 2.7
2036      */
2037     public static function save_grades_returns() {
2038         return null;
2039     }
2041     /**
2042      * Describes the parameters for copy_previous_attempt
2043      * @return external_external_function_parameters
2044      * @since  Moodle 2.6
2045      */
2046     public static function copy_previous_attempt_parameters() {
2047         return new external_function_parameters(
2048             array(
2049                 'assignmentid' => new external_value(PARAM_INT, 'The assignment id to operate on'),
2050             )
2051         );
2052     }
2054     /**
2055      * Copy a students previous attempt to a new attempt.
2056      *
2057      * @param int $assignmentid
2058      * @return array of warnings to indicate any errors.
2059      * @since Moodle 2.6
2060      */
2061     public static function copy_previous_attempt($assignmentid) {
2062         global $CFG, $USER;
2064         $params = self::validate_parameters(self::copy_previous_attempt_parameters(),
2065                                             array('assignmentid' => $assignmentid));
2067         $cm = get_coursemodule_from_instance('assign', $assignmentid, 0, false, MUST_EXIST);
2068         $context = context_module::instance($cm->id);
2069         self::validate_context($context);
2071         $assignment = new assign($context, $cm, null);
2073         $notices = array();
2075         $assignment->copy_previous_attempt($submissiondata, $notices);
2077         $warnings = array();
2078         foreach ($notices as $notice) {
2079             $warnings[] = self::generate_warning($assignmentid,
2080                                                  'couldnotcopyprevioussubmission',
2081                                                  $notice);
2082         }
2084         return $warnings;
2085     }
2087     /**
2088      * Describes the return value for save_submission
2089      *
2090      * @return external_single_structure
2091      * @since Moodle 2.6
2092      */
2093     public static function copy_previous_attempt_returns() {
2094         return new external_warnings();
2095     }
2097     /**
2098      * Returns description of method parameters
2099      *
2100      * @return external_function_parameters
2101      * @since Moodle 3.0
2102      */
2103     public static function view_grading_table_parameters() {
2104         return new external_function_parameters(
2105             array(
2106                 'assignid' => new external_value(PARAM_INT, 'assign instance id')
2107             )
2108         );
2109     }
2111     /**
2112      * Trigger the grading_table_viewed event.
2113      *
2114      * @param int $assignid the assign instance id
2115      * @return array of warnings and status result
2116      * @since Moodle 3.0
2117      * @throws moodle_exception
2118      */
2119     public static function view_grading_table($assignid) {
2120         global $DB, $CFG;
2122         $params = self::validate_parameters(self::view_grading_table_parameters(),
2123                                             array(
2124                                                 'assignid' => $assignid
2125                                             ));
2126         $warnings = array();
2128         // Request and permission validation.
2129         $assign = $DB->get_record('assign', array('id' => $params['assignid']), 'id', MUST_EXIST);
2130         list($course, $cm) = get_course_and_cm_from_instance($assign, 'assign');
2132         $context = context_module::instance($cm->id);
2133         self::validate_context($context);
2135         require_capability('mod/assign:view', $context);
2137         $assign = new assign($context, null, null);
2138         $assign->require_view_grades();
2139         \mod_assign\event\grading_table_viewed::create_from_assign($assign)->trigger();
2141         $result = array();
2142         $result['status'] = true;
2143         $result['warnings'] = $warnings;
2144         return $result;
2145     }
2147     /**
2148      * Returns description of method result value
2149      *
2150      * @return external_description
2151      * @since Moodle 3.0
2152      */
2153     public static function view_grading_table_returns() {
2154         return new external_single_structure(
2155             array(
2156                 'status' => new external_value(PARAM_BOOL, 'status: true if success'),
2157                 'warnings' => new external_warnings()
2158             )
2159         );
2160     }
2161     /**
2162      * Describes the parameters for view_submission_status.
2163      *
2164      * @return external_external_function_parameters
2165      * @since Moodle 3.1
2166      */
2167     public static function view_submission_status_parameters() {
2168         return new external_function_parameters (
2169             array(
2170                 'assignid' => new external_value(PARAM_INT, 'assign instance id'),
2171             )
2172         );
2173     }
2175     /**
2176      * Trigger the submission status viewed event.
2177      *
2178      * @param int $assignid assign instance id
2179      * @return array of warnings and status result
2180      * @since Moodle 3.1
2181      */
2182     public static function view_submission_status($assignid) {
2183         global $DB, $CFG;
2185         $warnings = array();
2186         $params = array(
2187             'assignid' => $assignid,
2188         );
2189         $params = self::validate_parameters(self::view_submission_status_parameters(), $params);
2191         // Request and permission validation.
2192         $assign = $DB->get_record('assign', array('id' => $params['assignid']), 'id', MUST_EXIST);
2193         list($course, $cm) = get_course_and_cm_from_instance($assign, 'assign');
2195         $context = context_module::instance($cm->id);
2196         // Please, note that is not required to check mod/assign:view because is done by validate_context->require_login.
2197         self::validate_context($context);
2199         $assign = new assign($context, $cm, $course);
2200         \mod_assign\event\submission_status_viewed::create_from_assign($assign)->trigger();
2202         $result = array();
2203         $result['status'] = true;
2204         $result['warnings'] = $warnings;
2205         return $result;
2206     }
2208     /**
2209      * Describes the view_submission_status return value.
2210      *
2211      * @return external_single_structure
2212      * @since Moodle 3.1
2213      */
2214     public static function view_submission_status_returns() {
2215         return new external_single_structure(
2216             array(
2217                 'status' => new external_value(PARAM_BOOL, 'status: true if success'),
2218                 'warnings' => new external_warnings(),
2219             )
2220         );
2221     }
2223     /**
2224      * Describes the parameters for get_submission_status.
2225      *
2226      * @return external_external_function_parameters
2227      * @since Moodle 3.1
2228      */
2229     public static function get_submission_status_parameters() {
2230         return new external_function_parameters (
2231             array(
2232                 'assignid' => new external_value(PARAM_INT, 'assignment instance id'),
2233                 'userid' => new external_value(PARAM_INT, 'user id (empty for current user)', VALUE_DEFAULT, 0),
2234             )
2235         );
2236     }
2238     /**
2239      * Returns information about an assignment submission status for a given user.
2240      *
2241      * @param int $assignid assignment instance id
2242      * @param int $userid user id (empty for current user)
2243      * @return array of warnings and grading, status, feedback and previous attempts information
2244      * @since Moodle 3.1
2245      * @throws required_capability_exception
2246      */
2247     public static function get_submission_status($assignid, $userid = 0) {
2248         global $USER, $DB;
2250         $warnings = array();
2252         $params = array(
2253             'assignid' => $assignid,
2254             'userid' => $userid,
2255         );
2256         $params = self::validate_parameters(self::get_submission_status_parameters(), $params);
2258         // Request and permission validation.
2259         $assign = $DB->get_record('assign', array('id' => $params['assignid']), 'id', MUST_EXIST);
2260         list($course, $cm) = get_course_and_cm_from_instance($assign, 'assign');
2262         $context = context_module::instance($cm->id);
2263         self::validate_context($context);
2265         $assign = new assign($context, $cm, $course);
2267         // Default value for userid.
2268         if (empty($params['userid'])) {
2269             $params['userid'] = $USER->id;
2270         }
2271         $user = core_user::get_user($params['userid'], '*', MUST_EXIST);
2272         core_user::require_active_user($user);
2274         if (!$assign->can_view_submission($user->id)) {
2275             throw new required_capability_exception($context, 'mod/assign:viewgrades', 'nopermission', '');
2276         }
2278         $gradingsummary = $lastattempt = $feedback = $previousattempts = null;
2280         // Get the renderable since it contais all the info we need.
2281         if ($assign->can_view_grades()) {
2282             $gradingsummary = $assign->get_assign_grading_summary_renderable();
2283         }
2285         // Retrieve the rest of the renderable objects.
2286         if (has_capability('mod/assign:submit', $assign->get_context(), $user)) {
2287             $lastattempt = $assign->get_assign_submission_status_renderable($user, true);
2288         }
2290         $feedback = $assign->get_assign_feedback_status_renderable($user);
2292         $previousattempts = $assign->get_assign_attempt_history_renderable($user);
2294         // Now, build the result.
2295         $result = array();
2297         // First of all, grading summary, this is suitable for teachers/managers.
2298         if ($gradingsummary) {
2299             $result['gradingsummary'] = $gradingsummary;
2300         }
2302         // Did we submit anything?
2303         if ($lastattempt) {
2304             $submissionplugins = $assign->get_submission_plugins();
2306             if (empty($lastattempt->submission)) {
2307                 unset($lastattempt->submission);
2308             } else {
2309                 $lastattempt->submission->plugins = self::get_plugins_data($assign, $submissionplugins, $lastattempt->submission);
2310             }
2312             if (empty($lastattempt->teamsubmission)) {
2313                 unset($lastattempt->teamsubmission);
2314             } else {
2315                 $lastattempt->teamsubmission->plugins = self::get_plugins_data($assign, $submissionplugins,
2316                                                                                 $lastattempt->teamsubmission);
2317             }
2319             // We need to change the type of some of the structures retrieved from the renderable.
2320             if (!empty($lastattempt->submissiongroup)) {
2321                 $lastattempt->submissiongroup = $lastattempt->submissiongroup->id;
2322             }
2323             if (!empty($lastattempt->usergroups)) {
2324                 $lastattempt->usergroups = array_keys($lastattempt->usergroups);
2325             }
2326             // We cannot use array_keys here.
2327             if (!empty($lastattempt->submissiongroupmemberswhoneedtosubmit)) {
2328                 $lastattempt->submissiongroupmemberswhoneedtosubmit = array_map(
2329                                                                             function($e){
2330                                                                                 return $e->id;
2331                                                                             },
2332                                                                             $lastattempt->submissiongroupmemberswhoneedtosubmit);
2333             }
2335             $result['lastattempt'] = $lastattempt;
2336         }
2338         // The feedback for our latest submission.
2339         if ($feedback) {
2340             if ($feedback->grade) {
2341                 $feedbackplugins = $assign->get_feedback_plugins();
2342                 $feedback->plugins = self::get_plugins_data($assign, $feedbackplugins, $feedback->grade);
2343             } else {
2344                 unset($feedback->plugins);
2345                 unset($feedback->grade);
2346             }
2348             $result['feedback'] = $feedback;
2349         }
2351         // Retrieve only previous attempts.
2352         if ($previousattempts and count($previousattempts->submissions) > 1) {
2353             // Don't show the last one because it is the current submission.
2354             array_pop($previousattempts->submissions);
2356             // Show newest to oldest.
2357             $previousattempts->submissions = array_reverse($previousattempts->submissions);
2359             foreach ($previousattempts->submissions as $i => $submission) {
2360                 $attempt = array();
2362                 $grade = null;
2363                 foreach ($previousattempts->grades as $onegrade) {
2364                     if ($onegrade->attemptnumber == $submission->attemptnumber) {
2365                         $grade = $onegrade;
2366                         break;
2367                     }
2368                 }
2370                 $attempt['attemptnumber'] = $submission->attemptnumber;
2372                 if ($submission) {
2373                     $submission->plugins = self::get_plugins_data($assign, $previousattempts->submissionplugins, $submission);
2374                     $attempt['submission'] = $submission;
2375                 }
2377                 if ($grade) {
2378                     // From object to id.
2379                     $grade->grader = $grade->grader->id;
2380                     $feedbackplugins = self::get_plugins_data($assign, $previousattempts->feedbackplugins, $grade);
2382                     $attempt['grade'] = $grade;
2383                     $attempt['feedbackplugins'] = $feedbackplugins;
2384                 }
2385                 $result['previousattempts'][] = $attempt;
2386             }
2387         }
2389         $result['warnings'] = $warnings;
2390         return $result;
2391     }
2393     /**
2394      * Describes the get_submission_status return value.
2395      *
2396      * @return external_single_structure
2397      * @since Moodle 3.1
2398      */
2399     public static function get_submission_status_returns() {
2400         return new external_single_structure(
2401             array(
2402                 'gradingsummary' => new external_single_structure(
2403                     array(
2404                         'participantcount' => new external_value(PARAM_INT, 'Number of users who can submit.'),
2405                         'submissiondraftscount' => new external_value(PARAM_INT, 'Number of submissions in draft status.'),
2406                         'submissiondraftscount' => new external_value(PARAM_INT, 'Number of submissions in draft status.'),
2407                         'submissionsenabled' => new external_value(PARAM_BOOL, 'Whether submissions are enabled or not.'),
2408                         'submissionssubmittedcount' => new external_value(PARAM_INT, 'Number of submissions in submitted status.'),
2409                         'submissionsneedgradingcount' => new external_value(PARAM_INT, 'Number of submissions that need grading.'),
2410                         'warnofungroupedusers' => new external_value(PARAM_BOOL, 'Whether we need to warn people that there
2411                                                                         are users without groups.'),
2412                     ), 'Grading information.', VALUE_OPTIONAL
2413                 ),
2414                 'lastattempt' => new external_single_structure(
2415                     array(
2416                         'submission' => self::get_submission_structure(VALUE_OPTIONAL),
2417                         'teamsubmission' => self::get_submission_structure(VALUE_OPTIONAL),
2418                         'submissiongroup' => new external_value(PARAM_INT, 'The submission group id (for group submissions only).',
2419                                                                 VALUE_OPTIONAL),
2420                         'submissiongroupmemberswhoneedtosubmit' => new external_multiple_structure(
2421                             new external_value(PARAM_INT, 'USER id.'),
2422                             'List of users who still need to submit (for group submissions only).',
2423                             VALUE_OPTIONAL
2424                         ),
2425                         'submissionsenabled' => new external_value(PARAM_BOOL, 'Whether submissions are enabled or not.'),
2426                         'locked' => new external_value(PARAM_BOOL, 'Whether new submissions are locked.'),
2427                         'graded' => new external_value(PARAM_BOOL, 'Whether the submission is graded.'),
2428                         'canedit' => new external_value(PARAM_BOOL, 'Whether the user can edit the current submission.'),
2429                         'cansubmit' => new external_value(PARAM_BOOL, 'Whether the user can submit.'),
2430                         'extensionduedate' => new external_value(PARAM_INT, 'Extension due date.'),
2431                         'blindmarking' => new external_value(PARAM_BOOL, 'Whether blind marking is enabled.'),
2432                         'gradingstatus' => new external_value(PARAM_ALPHANUMEXT, 'Grading status.'),
2433                         'usergroups' => new external_multiple_structure(
2434                             new external_value(PARAM_INT, 'Group id.'), 'User groups in the course.'
2435                         ),
2436                     ), 'Last attempt information.', VALUE_OPTIONAL
2437                 ),
2438                 'feedback' => new external_single_structure(
2439                     array(
2440                         'grade' => self::get_grade_structure(VALUE_OPTIONAL),
2441                         'gradefordisplay' => new external_value(PARAM_RAW, 'Grade rendered into a format suitable for display.'),
2442                         'gradeddate' => new external_value(PARAM_INT, 'The date the user was graded.'),
2443                         'plugins' => new external_multiple_structure(self::get_plugin_structure(), 'Plugins info.', VALUE_OPTIONAL),
2444                     ), 'Feedback for the last attempt.', VALUE_OPTIONAL
2445                 ),
2446                 'previousattempts' => new external_multiple_structure(
2447                     new external_single_structure(
2448                         array(
2449                             'attemptnumber' => new external_value(PARAM_INT, 'Attempt number.'),
2450                             'submission' => self::get_submission_structure(VALUE_OPTIONAL),
2451                             'grade' => self::get_grade_structure(VALUE_OPTIONAL),
2452                             'feedbackplugins' => new external_multiple_structure(self::get_plugin_structure(), 'Feedback info.',
2453                                                                                     VALUE_OPTIONAL),
2454                         )
2455                     ), 'List all the previous attempts did by the user.', VALUE_OPTIONAL
2456                 ),
2457                 'warnings' => new external_warnings(),
2458             )
2459         );
2460     }