2 // This file is part of Moodle - http://moodle.org/
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.
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.
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/>.
22 * @copyright 2012 Paul Charsley
23 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
26 defined('MOODLE_INTERNAL') || die;
28 require_once("$CFG->libdir/externallib.php");
29 require_once("$CFG->dirroot/user/externallib.php");
30 require_once("$CFG->dirroot/mod/assign/locallib.php");
34 * @copyright 2012 Paul Charsley
35 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
37 class mod_assign_external extends external_api {
40 * Generate a warning in a standard structure for a known failure.
42 * @param int $assignmentid - The assignment
43 * @param string $warningcode - The key for the warning message
44 * @param string $detail - A description of the error
45 * @return array - Warning structure containing item, itemid, warningcode, message
47 private static function generate_warning($assignmentid, $warningcode, $detail) {
48 $warningmessages = array(
49 'couldnotlock'=>'Could not lock the submission for this user.',
50 'couldnotunlock'=>'Could not unlock the submission for this user.',
51 'couldnotsubmitforgrading'=>'Could not submit assignment for grading.',
52 'couldnotrevealidentities'=>'Could not reveal identities.',
53 'couldnotgrantextensions'=>'Could not grant submission date extensions.',
54 'couldnotrevert'=>'Could not revert submission to draft.',
55 'invalidparameters'=>'Invalid parameters.',
56 'couldnotsavesubmission'=>'Could not save submission.',
57 'couldnotsavegrade'=>'Could not save grade.'
60 $message = $warningmessages[$warningcode];
61 if (empty($message)) {
62 $message = 'Unknown warning type.';
65 return array('item'=>$detail,
66 'itemid'=>$assignmentid,
67 'warningcode'=>$warningcode,
72 * Describes the parameters for get_grades
73 * @return external_external_function_parameters
76 public static function get_grades_parameters() {
77 return new external_function_parameters(
79 'assignmentids' => new external_multiple_structure(
80 new external_value(PARAM_INT, 'assignment id'),
81 '1 or more assignment ids',
83 'since' => new external_value(PARAM_INT,
84 'timestamp, only return records where timemodified >= since',
91 * Returns grade information from assign_grades for the requested assignment ids
92 * @param int[] $assignmentids
93 * @param int $since only return records with timemodified >= since
94 * @return array of grade records for each requested assignment
97 public static function get_grades($assignmentids, $since = 0) {
99 $params = self::validate_parameters(self::get_grades_parameters(),
100 array('assignmentids' => $assignmentids,
103 $assignments = array();
105 $requestedassignmentids = $params['assignmentids'];
107 // Check the user is allowed to get the grades for the assignments requested.
108 $placeholders = array();
109 list($sqlassignmentids, $placeholders) = $DB->get_in_or_equal($requestedassignmentids, SQL_PARAMS_NAMED);
110 $sql = "SELECT cm.id, cm.instance FROM {course_modules} cm JOIN {modules} md ON md.id = cm.module ".
111 "WHERE md.name = :modname AND cm.instance ".$sqlassignmentids;
112 $placeholders['modname'] = 'assign';
113 $cms = $DB->get_records_sql($sql, $placeholders);
114 foreach ($cms as $cm) {
116 $context = context_module::instance($cm->id);
117 self::validate_context($context);
118 require_capability('mod/assign:grade', $context);
119 } catch (Exception $e) {
120 $requestedassignmentids = array_diff($requestedassignmentids, array($cm->instance));
122 $warning['item'] = 'assignment';
123 $warning['itemid'] = $cm->instance;
124 $warning['warningcode'] = '1';
125 $warning['message'] = 'No access rights in module context';
126 $warnings[] = $warning;
130 // Create the query and populate an array of grade records from the recordset results.
131 if (count ($requestedassignmentids) > 0) {
132 $placeholders = array();
133 list($inorequalsql, $placeholders) = $DB->get_in_or_equal($requestedassignmentids, SQL_PARAMS_NAMED);
135 $sql = "SELECT ag.id,
143 FROM {assign_grades} ag, {assign_submission} s
144 WHERE s.assignment $inorequalsql
145 AND s.userid = ag.userid
147 AND s.attemptnumber = ag.attemptnumber
148 AND ag.timemodified >= :since
149 AND ag.assignment = s.assignment
150 ORDER BY ag.assignment, ag.id";
152 $placeholders['since'] = $params['since'];
153 $rs = $DB->get_recordset_sql($sql, $placeholders);
154 $currentassignmentid = null;
156 foreach ($rs as $rd) {
158 $grade['id'] = $rd->id;
159 $grade['userid'] = $rd->userid;
160 $grade['timecreated'] = $rd->timecreated;
161 $grade['timemodified'] = $rd->timemodified;
162 $grade['grader'] = $rd->grader;
163 $grade['attemptnumber'] = $rd->attemptnumber;
164 $grade['grade'] = (string)$rd->grade;
166 if (is_null($currentassignmentid) || ($rd->assignment != $currentassignmentid )) {
167 if (!is_null($assignment)) {
168 $assignments[] = $assignment;
170 $assignment = array();
171 $assignment['assignmentid'] = $rd->assignment;
172 $assignment['grades'] = array();
173 $requestedassignmentids = array_diff($requestedassignmentids, array($rd->assignment));
175 $assignment['grades'][] = $grade;
177 $currentassignmentid = $rd->assignment;
179 if (!is_null($assignment)) {
180 $assignments[] = $assignment;
184 foreach ($requestedassignmentids as $assignmentid) {
186 $warning['item'] = 'assignment';
187 $warning['itemid'] = $assignmentid;
188 $warning['warningcode'] = '3';
189 $warning['message'] = 'No grades found';
190 $warnings[] = $warning;
194 $result['assignments'] = $assignments;
195 $result['warnings'] = $warnings;
200 * Creates a grade single structure.
202 * @return external_single_structure a grade single structure.
205 private static function get_grade_structure($required = VALUE_REQUIRED) {
206 return new external_single_structure(
208 'id' => new external_value(PARAM_INT, 'grade id'),
209 'assignment' => new external_value(PARAM_INT, 'assignment id', VALUE_OPTIONAL),
210 'userid' => new external_value(PARAM_INT, 'student id'),
211 'attemptnumber' => new external_value(PARAM_INT, 'attempt number'),
212 'timecreated' => new external_value(PARAM_INT, 'grade creation time'),
213 'timemodified' => new external_value(PARAM_INT, 'grade last modified time'),
214 'grader' => new external_value(PARAM_INT, 'grader'),
215 'grade' => new external_value(PARAM_TEXT, 'grade'),
216 'gradefordisplay' => new external_value(PARAM_RAW, 'grade rendered into a format suitable for display',
218 ), 'grade information', $required
223 * Creates an assign_grades external_single_structure
224 * @return external_single_structure
227 private static function assign_grades() {
228 return new external_single_structure(
230 'assignmentid' => new external_value(PARAM_INT, 'assignment id'),
231 'grades' => new external_multiple_structure(self::get_grade_structure())
237 * Describes the get_grades return value
238 * @return external_single_structure
241 public static function get_grades_returns() {
242 return new external_single_structure(
244 'assignments' => new external_multiple_structure(self::assign_grades(), 'list of assignment grade information'),
245 'warnings' => new external_warnings('item is always \'assignment\'',
246 'when errorcode is 3 then itemid is an assignment id. When errorcode is 1, itemid is a course module id',
247 'errorcode can be 3 (no grades found) or 1 (no permission to get grades)')
253 * Returns description of method parameters
255 * @return external_function_parameters
258 public static function get_assignments_parameters() {
259 return new external_function_parameters(
261 'courseids' => new external_multiple_structure(
262 new external_value(PARAM_INT, 'course id, empty for retrieving all the courses where the user is enroled in'),
263 '0 or more course ids',
264 VALUE_DEFAULT, array()
266 'capabilities' => new external_multiple_structure(
267 new external_value(PARAM_CAPABILITY, 'capability'),
268 'list of capabilities used to filter courses',
269 VALUE_DEFAULT, array()
271 'includenotenrolledcourses' => new external_value(PARAM_BOOL, 'whether to return courses that the user can see
272 even if is not enroled in. This requires the parameter courseids
273 to not be empty.', VALUE_DEFAULT, false)
279 * Returns an array of courses the user is enrolled, and for each course all of the assignments that the user can
280 * view within that course.
282 * @param array $courseids An optional array of course ids. If provided only assignments within the given course
283 * will be returned. If the user is not enrolled in or can't view a given course a warning will be generated and returned.
284 * @param array $capabilities An array of additional capability checks you wish to be made on the course context.
285 * @param bool $includenotenrolledcourses Wheter to return courses that the user can see even if is not enroled in.
286 * This requires the parameter $courseids to not be empty.
287 * @return An array of courses and warnings.
290 public static function get_assignments($courseids = array(), $capabilities = array(), $includenotenrolledcourses = false) {
291 global $USER, $DB, $CFG;
293 $params = self::validate_parameters(
294 self::get_assignments_parameters(),
296 'courseids' => $courseids,
297 'capabilities' => $capabilities,
298 'includenotenrolledcourses' => $includenotenrolledcourses
304 $fields = 'sortorder,shortname,fullname,timemodified';
306 // If the courseids list is empty, we return only the courses where the user is enrolled in.
307 if (empty($params['courseids'])) {
308 $courses = enrol_get_users_courses($USER->id, true, $fields);
309 $courseids = array_keys($courses);
310 } else if ($includenotenrolledcourses) {
311 // In this case, we don't have to check here for enrolmnents. Maybe the user can see the course even if is not enrolled.
312 $courseids = $params['courseids'];
314 // We need to check for enrolments.
315 $mycourses = enrol_get_users_courses($USER->id, true, $fields);
316 $mycourseids = array_keys($mycourses);
318 foreach ($params['courseids'] as $courseid) {
319 if (!in_array($courseid, $mycourseids)) {
320 unset($courses[$courseid]);
323 'itemid' => $courseid,
324 'warningcode' => '2',
325 'message' => 'User is not enrolled or does not have requested capability'
328 $courses[$courseid] = $mycourses[$courseid];
331 $courseids = array_keys($courses);
334 foreach ($courseids as $cid) {
337 $context = context_course::instance($cid);
338 self::validate_context($context);
340 // Check if this course was already loaded (by enrol_get_users_courses).
341 if (!isset($courses[$cid])) {
342 $courses[$cid] = get_course($cid);
344 $courses[$cid]->contextid = $context->id;
345 } catch (Exception $e) {
346 unset($courses[$cid]);
350 'warningcode' => '1',
351 'message' => 'No access rights in course context '.$e->getMessage()
355 if (count($params['capabilities']) > 0 && !has_all_capabilities($params['capabilities'], $context)) {
356 unset($courses[$cid]);
359 $extrafields='m.id as assignmentid, ' .
361 'm.nosubmissions, ' .
362 'm.submissiondrafts, ' .
363 'm.sendnotifications, '.
364 'm.sendlatenotifications, ' .
365 'm.sendstudentnotifications, ' .
367 'm.allowsubmissionsfromdate, '.
370 'm.completionsubmit, ' .
372 'm.teamsubmission, ' .
373 'm.requireallteammemberssubmit, '.
374 'm.teamsubmissiongroupingid, ' .
376 'm.revealidentities, ' .
377 'm.attemptreopenmethod, '.
379 'm.markingworkflow, ' .
380 'm.markingallocation, ' .
381 'm.requiresubmissionstatement, '.
382 'm.preventsubmissionnotingroup, '.
385 $coursearray = array();
386 foreach ($courses as $id => $course) {
387 $assignmentarray = array();
388 // Get a list of assignments for the course.
389 if ($modules = get_coursemodules_in_course('assign', $courses[$id]->id, $extrafields)) {
390 foreach ($modules as $module) {
391 $context = context_module::instance($module->id);
393 self::validate_context($context);
394 require_capability('mod/assign:view', $context);
395 } catch (Exception $e) {
398 'itemid' => $module->id,
399 'warningcode' => '1',
400 'message' => 'No access rights in module context'
404 $configrecords = $DB->get_recordset('assign_plugin_config', array('assignment' => $module->assignmentid));
405 $configarray = array();
406 foreach ($configrecords as $configrecord) {
407 $configarray[] = array(
408 'id' => $configrecord->id,
409 'assignment' => $configrecord->assignment,
410 'plugin' => $configrecord->plugin,
411 'subtype' => $configrecord->subtype,
412 'name' => $configrecord->name,
413 'value' => $configrecord->value
416 $configrecords->close();
419 'id' => $module->assignmentid,
420 'cmid' => $module->id,
421 'course' => $module->course,
422 'name' => $module->name,
423 'nosubmissions' => $module->nosubmissions,
424 'submissiondrafts' => $module->submissiondrafts,
425 'sendnotifications' => $module->sendnotifications,
426 'sendlatenotifications' => $module->sendlatenotifications,
427 'sendstudentnotifications' => $module->sendstudentnotifications,
428 'duedate' => $module->duedate,
429 'allowsubmissionsfromdate' => $module->allowsubmissionsfromdate,
430 'grade' => $module->grade,
431 'timemodified' => $module->timemodified,
432 'completionsubmit' => $module->completionsubmit,
433 'cutoffdate' => $module->cutoffdate,
434 'teamsubmission' => $module->teamsubmission,
435 'requireallteammemberssubmit' => $module->requireallteammemberssubmit,
436 'teamsubmissiongroupingid' => $module->teamsubmissiongroupingid,
437 'blindmarking' => $module->blindmarking,
438 'revealidentities' => $module->revealidentities,
439 'attemptreopenmethod' => $module->attemptreopenmethod,
440 'maxattempts' => $module->maxattempts,
441 'markingworkflow' => $module->markingworkflow,
442 'markingallocation' => $module->markingallocation,
443 'requiresubmissionstatement' => $module->requiresubmissionstatement,
444 'preventsubmissionnotingroup' => $module->preventsubmissionnotingroup,
445 'configs' => $configarray
448 // Return or not intro and file attachments depending on the plugin settings.
449 $assign = new assign($context, null, null);
451 if ($assign->show_intro()) {
453 list($assignment['intro'], $assignment['introformat']) = external_format_text($module->intro,
454 $module->introformat, $context->id, 'mod_assign', 'intro', null);
455 $assignment['introfiles'] = external_util::get_area_files($context->id, 'mod_assign', 'intro', false,
458 $fs = get_file_storage();
459 if ($files = $fs->get_area_files($context->id, 'mod_assign', ASSIGN_INTROATTACHMENT_FILEAREA,
460 0, 'timemodified', false)) {
462 $assignment['introattachments'] = array();
463 foreach ($files as $file) {
464 $filename = $file->get_filename();
466 $assignment['introattachments'][] = array(
467 'filename' => $filename,
468 'mimetype' => $file->get_mimetype(),
469 'fileurl' => moodle_url::make_webservice_pluginfile_url(
470 $context->id, 'mod_assign', ASSIGN_INTROATTACHMENT_FILEAREA, 0, '/', $filename)->out(false)
476 $assignmentarray[] = $assignment;
479 $coursearray[]= array(
480 'id' => $courses[$id]->id,
481 'fullname' => external_format_string($courses[$id]->fullname, $course->contextid),
482 'shortname' => external_format_string($courses[$id]->shortname, $course->contextid),
483 'timemodified' => $courses[$id]->timemodified,
484 'assignments' => $assignmentarray
489 'courses' => $coursearray,
490 'warnings' => $warnings
496 * Creates an assignment external_single_structure
498 * @return external_single_structure
501 private static function get_assignments_assignment_structure() {
502 return new external_single_structure(
504 'id' => new external_value(PARAM_INT, 'assignment id'),
505 'cmid' => new external_value(PARAM_INT, 'course module id'),
506 'course' => new external_value(PARAM_INT, 'course id'),
507 'name' => new external_value(PARAM_TEXT, 'assignment name'),
508 'nosubmissions' => new external_value(PARAM_INT, 'no submissions'),
509 'submissiondrafts' => new external_value(PARAM_INT, 'submissions drafts'),
510 'sendnotifications' => new external_value(PARAM_INT, 'send notifications'),
511 'sendlatenotifications' => new external_value(PARAM_INT, 'send notifications'),
512 'sendstudentnotifications' => new external_value(PARAM_INT, 'send student notifications (default)'),
513 'duedate' => new external_value(PARAM_INT, 'assignment due date'),
514 'allowsubmissionsfromdate' => new external_value(PARAM_INT, 'allow submissions from date'),
515 'grade' => new external_value(PARAM_INT, 'grade type'),
516 'timemodified' => new external_value(PARAM_INT, 'last time assignment was modified'),
517 'completionsubmit' => new external_value(PARAM_INT, 'if enabled, set activity as complete following submission'),
518 'cutoffdate' => new external_value(PARAM_INT, 'date after which submission is not accepted without an extension'),
519 'teamsubmission' => new external_value(PARAM_INT, 'if enabled, students submit as a team'),
520 'requireallteammemberssubmit' => new external_value(PARAM_INT, 'if enabled, all team members must submit'),
521 'teamsubmissiongroupingid' => new external_value(PARAM_INT, 'the grouping id for the team submission groups'),
522 'blindmarking' => new external_value(PARAM_INT, 'if enabled, hide identities until reveal identities actioned'),
523 'revealidentities' => new external_value(PARAM_INT, 'show identities for a blind marking assignment'),
524 'attemptreopenmethod' => new external_value(PARAM_TEXT, 'method used to control opening new attempts'),
525 'maxattempts' => new external_value(PARAM_INT, 'maximum number of attempts allowed'),
526 'markingworkflow' => new external_value(PARAM_INT, 'enable marking workflow'),
527 'markingallocation' => new external_value(PARAM_INT, 'enable marking allocation'),
528 'requiresubmissionstatement' => new external_value(PARAM_INT, 'student must accept submission statement'),
529 'preventsubmissionnotingroup' => new external_value(PARAM_INT, 'Prevent submission not in group', VALUE_OPTIONAL),
530 'configs' => new external_multiple_structure(self::get_assignments_config_structure(), 'configuration settings'),
531 'intro' => new external_value(PARAM_RAW,
532 'assignment intro, not allways returned because it deppends on the activity configuration', VALUE_OPTIONAL),
533 'introformat' => new external_format_value('intro', VALUE_OPTIONAL),
534 'introfiles' => new external_files('Files in the introduction text', VALUE_OPTIONAL),
535 'introattachments' => new external_multiple_structure(
536 new external_single_structure(
538 'filename' => new external_value(PARAM_FILE, 'file name'),
539 'mimetype' => new external_value(PARAM_RAW, 'mime type'),
540 'fileurl' => new external_value(PARAM_URL, 'file download url')
542 ), 'intro attachments files', VALUE_OPTIONAL
544 ), 'assignment information object');
548 * Creates an assign_plugin_config external_single_structure
550 * @return external_single_structure
553 private static function get_assignments_config_structure() {
554 return new external_single_structure(
556 'id' => new external_value(PARAM_INT, 'assign_plugin_config id'),
557 'assignment' => new external_value(PARAM_INT, 'assignment id'),
558 'plugin' => new external_value(PARAM_TEXT, 'plugin'),
559 'subtype' => new external_value(PARAM_TEXT, 'subtype'),
560 'name' => new external_value(PARAM_TEXT, 'name'),
561 'value' => new external_value(PARAM_TEXT, 'value')
562 ), 'assignment configuration object'
567 * Creates a course external_single_structure
569 * @return external_single_structure
572 private static function get_assignments_course_structure() {
573 return new external_single_structure(
575 'id' => new external_value(PARAM_INT, 'course id'),
576 'fullname' => new external_value(PARAM_TEXT, 'course full name'),
577 'shortname' => new external_value(PARAM_TEXT, 'course short name'),
578 'timemodified' => new external_value(PARAM_INT, 'last time modified'),
579 'assignments' => new external_multiple_structure(self::get_assignments_assignment_structure(), 'assignment info')
580 ), 'course information object'
585 * Describes the return value for get_assignments
587 * @return external_single_structure
590 public static function get_assignments_returns() {
591 return new external_single_structure(
593 'courses' => new external_multiple_structure(self::get_assignments_course_structure(), 'list of courses'),
594 'warnings' => new external_warnings('item can be \'course\' (errorcode 1 or 2) or \'module\' (errorcode 1)',
595 'When item is a course then itemid is a course id. When the item is a module then itemid is a module id',
596 'errorcode can be 1 (no access rights) or 2 (not enrolled or no permissions)')
602 * Return information (files and text fields) for the given plugins in the assignment.
604 * @param assign $assign the assignment object
605 * @param array $assignplugins array of assignment plugins (submission or feedback)
606 * @param stdClass $item the item object (submission or grade)
607 * @return array an array containing the plugins returned information
609 private static function get_plugins_data($assign, $assignplugins, $item) {
613 $fs = get_file_storage();
615 foreach ($assignplugins as $assignplugin) {
617 if (!$assignplugin->is_enabled() or !$assignplugin->is_visible()) {
622 'name' => $assignplugin->get_name(),
623 'type' => $assignplugin->get_type()
625 // Subtype is 'assignsubmission', type is currently 'file' or 'onlinetext'.
626 $component = $assignplugin->get_subtype().'_'.$assignplugin->get_type();
628 $fileareas = $assignplugin->get_file_areas();
629 foreach ($fileareas as $filearea => $name) {
630 $fileareainfo = array('area' => $filearea);
631 $files = $fs->get_area_files(
632 $assign->get_context()->id,
639 foreach ($files as $file) {
640 $filepath = $file->get_filepath().$file->get_filename();
641 $fileurl = file_encode_url($CFG->wwwroot . '/webservice/pluginfile.php', '/' . $assign->get_context()->id .
642 '/' . $component. '/'. $filearea . '/' . $item->id . $filepath);
644 'filepath' => $filepath,
645 'fileurl' => $fileurl
647 $fileareainfo['files'][] = $fileinfo;
649 $plugin['fileareas'][] = $fileareainfo;
652 $editorfields = $assignplugin->get_editor_fields();
653 foreach ($editorfields as $name => $description) {
654 $editorfieldinfo = array(
656 'description' => $description,
657 'text' => $assignplugin->get_editor_text($name, $item->id),
658 'format' => $assignplugin->get_editor_format($name, $item->id)
660 $plugin['editorfields'][] = $editorfieldinfo;
662 $plugins[] = $plugin;
668 * Describes the parameters for get_submissions
670 * @return external_external_function_parameters
673 public static function get_submissions_parameters() {
674 return new external_function_parameters(
676 'assignmentids' => new external_multiple_structure(
677 new external_value(PARAM_INT, 'assignment id'),
678 '1 or more assignment ids',
680 'status' => new external_value(PARAM_ALPHA, 'status', VALUE_DEFAULT, ''),
681 'since' => new external_value(PARAM_INT, 'submitted since', VALUE_DEFAULT, 0),
682 'before' => new external_value(PARAM_INT, 'submitted before', VALUE_DEFAULT, 0)
688 * Returns submissions for the requested assignment ids
690 * @param int[] $assignmentids
691 * @param string $status only return submissions with this status
692 * @param int $since only return submissions with timemodified >= since
693 * @param int $before only return submissions with timemodified <= before
694 * @return array of submissions for each requested assignment
697 public static function get_submissions($assignmentids, $status = '', $since = 0, $before = 0) {
700 $params = self::validate_parameters(self::get_submissions_parameters(),
701 array('assignmentids' => $assignmentids,
704 'before' => $before));
707 $assignments = array();
709 // Check the user is allowed to get the submissions for the assignments requested.
710 $placeholders = array();
711 list($inorequalsql, $placeholders) = $DB->get_in_or_equal($params['assignmentids'], SQL_PARAMS_NAMED);
712 $sql = "SELECT cm.id, cm.instance FROM {course_modules} cm JOIN {modules} md ON md.id = cm.module ".
713 "WHERE md.name = :modname AND cm.instance ".$inorequalsql;
714 $placeholders['modname'] = 'assign';
715 $cms = $DB->get_records_sql($sql, $placeholders);
717 foreach ($cms as $cm) {
719 $context = context_module::instance($cm->id);
720 self::validate_context($context);
721 require_capability('mod/assign:grade', $context);
722 $assign = new assign($context, null, null);
723 $assigns[] = $assign;
724 } catch (Exception $e) {
726 'item' => 'assignment',
727 'itemid' => $cm->instance,
728 'warningcode' => '1',
729 'message' => 'No access rights in module context'
734 foreach ($assigns as $assign) {
735 $submissions = array();
736 $placeholders = array('assignid1' => $assign->get_instance()->id,
737 'assignid2' => $assign->get_instance()->id);
739 $submissionmaxattempt = 'SELECT mxs.userid, MAX(mxs.attemptnumber) AS maxattempt
740 FROM {assign_submission} mxs
741 WHERE mxs.assignment = :assignid1 GROUP BY mxs.userid';
743 $sql = "SELECT mas.id, mas.assignment,mas.userid,".
744 "mas.timecreated,mas.timemodified,mas.status,mas.groupid,mas.attemptnumber ".
745 "FROM {assign_submission} mas ".
746 "JOIN ( " . $submissionmaxattempt . " ) smx ON mas.userid = smx.userid ".
747 "WHERE mas.assignment = :assignid2 AND mas.attemptnumber = smx.maxattempt";
749 if (!empty($params['status'])) {
750 $placeholders['status'] = $params['status'];
751 $sql = $sql." AND mas.status = :status";
753 if (!empty($params['before'])) {
754 $placeholders['since'] = $params['since'];
755 $placeholders['before'] = $params['before'];
756 $sql = $sql." AND mas.timemodified BETWEEN :since AND :before";
758 $placeholders['since'] = $params['since'];
759 $sql = $sql." AND mas.timemodified >= :since";
762 $submissionrecords = $DB->get_records_sql($sql, $placeholders);
764 if (!empty($submissionrecords)) {
765 $submissionplugins = $assign->get_submission_plugins();
766 foreach ($submissionrecords as $submissionrecord) {
768 'id' => $submissionrecord->id,
769 'userid' => $submissionrecord->userid,
770 'timecreated' => $submissionrecord->timecreated,
771 'timemodified' => $submissionrecord->timemodified,
772 'status' => $submissionrecord->status,
773 'attemptnumber' => $submissionrecord->attemptnumber,
774 'groupid' => $submissionrecord->groupid,
775 'plugins' => self::get_plugins_data($assign, $submissionplugins, $submissionrecord)
777 $submissions[] = $submission;
782 'itemid' => $assign->get_instance()->id,
783 'warningcode' => '3',
784 'message' => 'No submissions found'
788 $assignments[] = array(
789 'assignmentid' => $assign->get_instance()->id,
790 'submissions' => $submissions
796 'assignments' => $assignments,
797 'warnings' => $warnings
803 * Creates an assignment plugin structure.
805 * @return external_single_structure the plugin structure
807 private static function get_plugin_structure() {
808 return new external_single_structure(
810 'type' => new external_value(PARAM_TEXT, 'submission plugin type'),
811 'name' => new external_value(PARAM_TEXT, 'submission plugin name'),
812 'fileareas' => new external_multiple_structure(
813 new external_single_structure(
815 'area' => new external_value (PARAM_TEXT, 'file area'),
816 'files' => new external_multiple_structure(
817 new external_single_structure(
819 'filepath' => new external_value (PARAM_TEXT, 'file path'),
820 'fileurl' => new external_value (PARAM_URL, 'file download url',
823 ), 'files', VALUE_OPTIONAL
826 ), 'fileareas', VALUE_OPTIONAL
828 'editorfields' => new external_multiple_structure(
829 new external_single_structure(
831 'name' => new external_value(PARAM_TEXT, 'field name'),
832 'description' => new external_value(PARAM_TEXT, 'field description'),
833 'text' => new external_value (PARAM_RAW, 'field value'),
834 'format' => new external_format_value ('text')
837 , 'editorfields', VALUE_OPTIONAL
844 * Creates a submission structure.
846 * @return external_single_structure the submission structure
848 private static function get_submission_structure($required = VALUE_REQUIRED) {
849 return new external_single_structure(
851 'id' => new external_value(PARAM_INT, 'submission id'),
852 'userid' => new external_value(PARAM_INT, 'student id'),
853 'attemptnumber' => new external_value(PARAM_INT, 'attempt number'),
854 'timecreated' => new external_value(PARAM_INT, 'submission creation time'),
855 'timemodified' => new external_value(PARAM_INT, 'submission last modified time'),
856 'status' => new external_value(PARAM_TEXT, 'submission status'),
857 'groupid' => new external_value(PARAM_INT, 'group id'),
858 'assignment' => new external_value(PARAM_INT, 'assignment id', VALUE_OPTIONAL),
859 'latest' => new external_value(PARAM_INT, 'latest attempt', VALUE_OPTIONAL),
860 'plugins' => new external_multiple_structure(self::get_plugin_structure(), 'plugins', VALUE_OPTIONAL)
861 ), 'submission info', $required
866 * Creates an assign_submissions external_single_structure
868 * @return external_single_structure
871 private static function get_submissions_structure() {
872 return new external_single_structure(
874 'assignmentid' => new external_value(PARAM_INT, 'assignment id'),
875 'submissions' => new external_multiple_structure(self::get_submission_structure())
881 * Describes the get_submissions return value
883 * @return external_single_structure
886 public static function get_submissions_returns() {
887 return new external_single_structure(
889 'assignments' => new external_multiple_structure(self::get_submissions_structure(), 'assignment submissions'),
890 'warnings' => new external_warnings()
896 * Describes the parameters for set_user_flags
897 * @return external_function_parameters
900 public static function set_user_flags_parameters() {
901 return new external_function_parameters(
903 'assignmentid' => new external_value(PARAM_INT, 'assignment id'),
904 'userflags' => new external_multiple_structure(
905 new external_single_structure(
907 'userid' => new external_value(PARAM_INT, 'student id'),
908 'locked' => new external_value(PARAM_INT, 'locked', VALUE_OPTIONAL),
909 'mailed' => new external_value(PARAM_INT, 'mailed', VALUE_OPTIONAL),
910 'extensionduedate' => new external_value(PARAM_INT, 'extension due date', VALUE_OPTIONAL),
911 'workflowstate' => new external_value(PARAM_TEXT, 'marking workflow state', VALUE_OPTIONAL),
912 'allocatedmarker' => new external_value(PARAM_INT, 'allocated marker', VALUE_OPTIONAL)
921 * Create or update user_flags records
923 * @param int $assignmentid the assignment for which the userflags are created or updated
924 * @param array $userflags An array of userflags to create or update
925 * @return array containing success or failure information for each record
928 public static function set_user_flags($assignmentid, $userflags = array()) {
931 $params = self::validate_parameters(self::set_user_flags_parameters(),
932 array('assignmentid' => $assignmentid,
933 'userflags' => $userflags));
935 // Load assignment if it exists and if the user has the capability.
936 list($assign, $course, $cm, $context) = self::validate_assign($params['assignmentid']);
937 require_capability('mod/assign:grade', $context);
940 foreach ($params['userflags'] as $userflag) {
944 $record = $assign->get_user_flags($userflag['userid'], false);
946 if (isset($userflag['locked'])) {
947 $record->locked = $userflag['locked'];
949 if (isset($userflag['mailed'])) {
950 $record->mailed = $userflag['mailed'];
952 if (isset($userflag['extensionduedate'])) {
953 $record->extensionduedate = $userflag['extensionduedate'];
955 if (isset($userflag['workflowstate'])) {
956 $record->workflowstate = $userflag['workflowstate'];
958 if (isset($userflag['allocatedmarker'])) {
959 $record->allocatedmarker = $userflag['allocatedmarker'];
961 if ($assign->update_user_flags($record)) {
962 $result['id'] = $record->id;
963 $result['userid'] = $userflag['userid'];
965 $result['id'] = $record->id;
966 $result['userid'] = $userflag['userid'];
967 $result['errormessage'] = 'Record created but values could not be set';
970 $record = $assign->get_user_flags($userflag['userid'], true);
971 $setfields = isset($userflag['locked'])
972 || isset($userflag['mailed'])
973 || isset($userflag['extensionduedate'])
974 || isset($userflag['workflowstate'])
975 || isset($userflag['allocatedmarker']);
978 if (isset($userflag['locked'])) {
979 $record->locked = $userflag['locked'];
981 if (isset($userflag['mailed'])) {
982 $record->mailed = $userflag['mailed'];
984 if (isset($userflag['extensionduedate'])) {
985 $record->extensionduedate = $userflag['extensionduedate'];
987 if (isset($userflag['workflowstate'])) {
988 $record->workflowstate = $userflag['workflowstate'];
990 if (isset($userflag['allocatedmarker'])) {
991 $record->allocatedmarker = $userflag['allocatedmarker'];
993 if ($assign->update_user_flags($record)) {
994 $result['id'] = $record->id;
995 $result['userid'] = $userflag['userid'];
997 $result['id'] = $record->id;
998 $result['userid'] = $userflag['userid'];
999 $result['errormessage'] = 'Record created but values could not be set';
1002 $result['id'] = $record->id;
1003 $result['userid'] = $userflag['userid'];
1007 $result['userid'] = $userflag['userid'];
1008 $result['errormessage'] = 'Record could not be created';
1012 $results[] = $result;
1018 * Describes the set_user_flags return value
1019 * @return external_multiple_structure
1022 public static function set_user_flags_returns() {
1023 return new external_multiple_structure(
1024 new external_single_structure(
1026 'id' => new external_value(PARAM_INT, 'id of record if successful, -1 for failure'),
1027 'userid' => new external_value(PARAM_INT, 'userid of record'),
1028 'errormessage' => new external_value(PARAM_TEXT, 'Failure error message', VALUE_OPTIONAL)
1035 * Describes the parameters for get_user_flags
1036 * @return external_function_parameters
1039 public static function get_user_flags_parameters() {
1040 return new external_function_parameters(
1042 'assignmentids' => new external_multiple_structure(
1043 new external_value(PARAM_INT, 'assignment id'),
1044 '1 or more assignment ids',
1051 * Returns user flag information from assign_user_flags for the requested assignment ids
1052 * @param int[] $assignmentids
1053 * @return array of user flag records for each requested assignment
1056 public static function get_user_flags($assignmentids) {
1058 $params = self::validate_parameters(self::get_user_flags_parameters(),
1059 array('assignmentids' => $assignmentids));
1061 $assignments = array();
1062 $warnings = array();
1063 $requestedassignmentids = $params['assignmentids'];
1065 // Check the user is allowed to get the user flags for the assignments requested.
1066 $placeholders = array();
1067 list($sqlassignmentids, $placeholders) = $DB->get_in_or_equal($requestedassignmentids, SQL_PARAMS_NAMED);
1068 $sql = "SELECT cm.id, cm.instance FROM {course_modules} cm JOIN {modules} md ON md.id = cm.module ".
1069 "WHERE md.name = :modname AND cm.instance ".$sqlassignmentids;
1070 $placeholders['modname'] = 'assign';
1071 $cms = $DB->get_records_sql($sql, $placeholders);
1072 foreach ($cms as $cm) {
1074 $context = context_module::instance($cm->id);
1075 self::validate_context($context);
1076 require_capability('mod/assign:grade', $context);
1077 } catch (Exception $e) {
1078 $requestedassignmentids = array_diff($requestedassignmentids, array($cm->instance));
1080 $warning['item'] = 'assignment';
1081 $warning['itemid'] = $cm->instance;
1082 $warning['warningcode'] = '1';
1083 $warning['message'] = 'No access rights in module context';
1084 $warnings[] = $warning;
1088 // Create the query and populate an array of assign_user_flags records from the recordset results.
1089 if (count ($requestedassignmentids) > 0) {
1090 $placeholders = array();
1091 list($inorequalsql, $placeholders) = $DB->get_in_or_equal($requestedassignmentids, SQL_PARAMS_NAMED);
1093 $sql = "SELECT auf.id,auf.assignment,auf.userid,auf.locked,auf.mailed,".
1094 "auf.extensionduedate,auf.workflowstate,auf.allocatedmarker ".
1095 "FROM {assign_user_flags} auf ".
1096 "WHERE auf.assignment ".$inorequalsql.
1097 " ORDER BY auf.assignment, auf.id";
1099 $rs = $DB->get_recordset_sql($sql, $placeholders);
1100 $currentassignmentid = null;
1102 foreach ($rs as $rd) {
1103 $userflag = array();
1104 $userflag['id'] = $rd->id;
1105 $userflag['userid'] = $rd->userid;
1106 $userflag['locked'] = $rd->locked;
1107 $userflag['mailed'] = $rd->mailed;
1108 $userflag['extensionduedate'] = $rd->extensionduedate;
1109 $userflag['workflowstate'] = $rd->workflowstate;
1110 $userflag['allocatedmarker'] = $rd->allocatedmarker;
1112 if (is_null($currentassignmentid) || ($rd->assignment != $currentassignmentid )) {
1113 if (!is_null($assignment)) {
1114 $assignments[] = $assignment;
1116 $assignment = array();
1117 $assignment['assignmentid'] = $rd->assignment;
1118 $assignment['userflags'] = array();
1119 $requestedassignmentids = array_diff($requestedassignmentids, array($rd->assignment));
1121 $assignment['userflags'][] = $userflag;
1123 $currentassignmentid = $rd->assignment;
1125 if (!is_null($assignment)) {
1126 $assignments[] = $assignment;
1132 foreach ($requestedassignmentids as $assignmentid) {
1134 $warning['item'] = 'assignment';
1135 $warning['itemid'] = $assignmentid;
1136 $warning['warningcode'] = '3';
1137 $warning['message'] = 'No user flags found';
1138 $warnings[] = $warning;
1142 $result['assignments'] = $assignments;
1143 $result['warnings'] = $warnings;
1148 * Creates an assign_user_flags external_single_structure
1149 * @return external_single_structure
1152 private static function assign_user_flags() {
1153 return new external_single_structure(
1155 'assignmentid' => new external_value(PARAM_INT, 'assignment id'),
1156 'userflags' => new external_multiple_structure(new external_single_structure(
1158 'id' => new external_value(PARAM_INT, 'user flag id'),
1159 'userid' => new external_value(PARAM_INT, 'student id'),
1160 'locked' => new external_value(PARAM_INT, 'locked'),
1161 'mailed' => new external_value(PARAM_INT, 'mailed'),
1162 'extensionduedate' => new external_value(PARAM_INT, 'extension due date'),
1163 'workflowstate' => new external_value(PARAM_TEXT, 'marking workflow state', VALUE_OPTIONAL),
1164 'allocatedmarker' => new external_value(PARAM_INT, 'allocated marker')
1173 * Describes the get_user_flags return value
1174 * @return external_single_structure
1177 public static function get_user_flags_returns() {
1178 return new external_single_structure(
1180 'assignments' => new external_multiple_structure(self::assign_user_flags(), 'list of assign user flag information'),
1181 'warnings' => new external_warnings('item is always \'assignment\'',
1182 'when errorcode is 3 then itemid is an assignment id. When errorcode is 1, itemid is a course module id',
1183 'errorcode can be 3 (no user flags found) or 1 (no permission to get user flags)')
1189 * Describes the parameters for get_user_mappings
1190 * @return external_function_parameters
1193 public static function get_user_mappings_parameters() {
1194 return new external_function_parameters(
1196 'assignmentids' => new external_multiple_structure(
1197 new external_value(PARAM_INT, 'assignment id'),
1198 '1 or more assignment ids',
1205 * Returns user mapping information from assign_user_mapping for the requested assignment ids
1206 * @param int[] $assignmentids
1207 * @return array of user mapping records for each requested assignment
1210 public static function get_user_mappings($assignmentids) {
1212 $params = self::validate_parameters(self::get_user_mappings_parameters(),
1213 array('assignmentids' => $assignmentids));
1215 $assignments = array();
1216 $warnings = array();
1217 $requestedassignmentids = $params['assignmentids'];
1219 // Check the user is allowed to get the mappings for the assignments requested.
1220 $placeholders = array();
1221 list($sqlassignmentids, $placeholders) = $DB->get_in_or_equal($requestedassignmentids, SQL_PARAMS_NAMED);
1222 $sql = "SELECT cm.id, cm.instance FROM {course_modules} cm JOIN {modules} md ON md.id = cm.module ".
1223 "WHERE md.name = :modname AND cm.instance ".$sqlassignmentids;
1224 $placeholders['modname'] = 'assign';
1225 $cms = $DB->get_records_sql($sql, $placeholders);
1226 foreach ($cms as $cm) {
1228 $context = context_module::instance($cm->id);
1229 self::validate_context($context);
1230 require_capability('mod/assign:revealidentities', $context);
1231 } catch (Exception $e) {
1232 $requestedassignmentids = array_diff($requestedassignmentids, array($cm->instance));
1234 $warning['item'] = 'assignment';
1235 $warning['itemid'] = $cm->instance;
1236 $warning['warningcode'] = '1';
1237 $warning['message'] = 'No access rights in module context';
1238 $warnings[] = $warning;
1242 // Create the query and populate an array of assign_user_mapping records from the recordset results.
1243 if (count ($requestedassignmentids) > 0) {
1244 $placeholders = array();
1245 list($inorequalsql, $placeholders) = $DB->get_in_or_equal($requestedassignmentids, SQL_PARAMS_NAMED);
1247 $sql = "SELECT aum.id,aum.assignment,aum.userid ".
1248 "FROM {assign_user_mapping} aum ".
1249 "WHERE aum.assignment ".$inorequalsql.
1250 " ORDER BY aum.assignment, aum.id";
1252 $rs = $DB->get_recordset_sql($sql, $placeholders);
1253 $currentassignmentid = null;
1255 foreach ($rs as $rd) {
1257 $mapping['id'] = $rd->id;
1258 $mapping['userid'] = $rd->userid;
1260 if (is_null($currentassignmentid) || ($rd->assignment != $currentassignmentid )) {
1261 if (!is_null($assignment)) {
1262 $assignments[] = $assignment;
1264 $assignment = array();
1265 $assignment['assignmentid'] = $rd->assignment;
1266 $assignment['mappings'] = array();
1267 $requestedassignmentids = array_diff($requestedassignmentids, array($rd->assignment));
1269 $assignment['mappings'][] = $mapping;
1271 $currentassignmentid = $rd->assignment;
1273 if (!is_null($assignment)) {
1274 $assignments[] = $assignment;
1280 foreach ($requestedassignmentids as $assignmentid) {
1282 $warning['item'] = 'assignment';
1283 $warning['itemid'] = $assignmentid;
1284 $warning['warningcode'] = '3';
1285 $warning['message'] = 'No mappings found';
1286 $warnings[] = $warning;
1290 $result['assignments'] = $assignments;
1291 $result['warnings'] = $warnings;
1296 * Creates an assign_user_mappings external_single_structure
1297 * @return external_single_structure
1300 private static function assign_user_mappings() {
1301 return new external_single_structure(
1303 'assignmentid' => new external_value(PARAM_INT, 'assignment id'),
1304 'mappings' => new external_multiple_structure(new external_single_structure(
1306 'id' => new external_value(PARAM_INT, 'user mapping id'),
1307 'userid' => new external_value(PARAM_INT, 'student id')
1316 * Describes the get_user_mappings return value
1317 * @return external_single_structure
1320 public static function get_user_mappings_returns() {
1321 return new external_single_structure(
1323 'assignments' => new external_multiple_structure(self::assign_user_mappings(), 'list of assign user mapping data'),
1324 'warnings' => new external_warnings('item is always \'assignment\'',
1325 'when errorcode is 3 then itemid is an assignment id. When errorcode is 1, itemid is a course module id',
1326 'errorcode can be 3 (no user mappings found) or 1 (no permission to get user mappings)')
1332 * Describes the parameters for lock_submissions
1333 * @return external_external_function_parameters
1336 public static function lock_submissions_parameters() {
1337 return new external_function_parameters(
1339 'assignmentid' => new external_value(PARAM_INT, 'The assignment id to operate on'),
1340 'userids' => new external_multiple_structure(
1341 new external_value(PARAM_INT, 'user id'),
1342 '1 or more user ids',
1349 * Locks (prevent updates to) submissions in this assignment.
1351 * @param int $assignmentid The id of the assignment
1352 * @param array $userids Array of user ids to lock
1353 * @return array of warnings for each submission that could not be locked.
1356 public static function lock_submissions($assignmentid, $userids) {
1359 $params = self::validate_parameters(self::lock_submissions_parameters(),
1360 array('assignmentid' => $assignmentid,
1361 'userids' => $userids));
1363 list($assignment, $course, $cm, $context) = self::validate_assign($params['assignmentid']);
1365 $warnings = array();
1366 foreach ($params['userids'] as $userid) {
1367 if (!$assignment->lock_submission($userid)) {
1368 $detail = 'User id: ' . $userid . ', Assignment id: ' . $params['assignmentid'];
1369 $warnings[] = self::generate_warning($params['assignmentid'],
1379 * Describes the return value for lock_submissions
1381 * @return external_single_structure
1384 public static function lock_submissions_returns() {
1385 return new external_warnings();
1389 * Describes the parameters for revert_submissions_to_draft
1390 * @return external_external_function_parameters
1393 public static function revert_submissions_to_draft_parameters() {
1394 return new external_function_parameters(
1396 'assignmentid' => new external_value(PARAM_INT, 'The assignment id to operate on'),
1397 'userids' => new external_multiple_structure(
1398 new external_value(PARAM_INT, 'user id'),
1399 '1 or more user ids',
1406 * Reverts a list of user submissions to draft for a single assignment.
1408 * @param int $assignmentid The id of the assignment
1409 * @param array $userids Array of user ids to revert
1410 * @return array of warnings for each submission that could not be reverted.
1413 public static function revert_submissions_to_draft($assignmentid, $userids) {
1416 $params = self::validate_parameters(self::revert_submissions_to_draft_parameters(),
1417 array('assignmentid' => $assignmentid,
1418 'userids' => $userids));
1420 list($assignment, $course, $cm, $context) = self::validate_assign($params['assignmentid']);
1422 $warnings = array();
1423 foreach ($params['userids'] as $userid) {
1424 if (!$assignment->revert_to_draft($userid)) {
1425 $detail = 'User id: ' . $userid . ', Assignment id: ' . $params['assignmentid'];
1426 $warnings[] = self::generate_warning($params['assignmentid'],
1436 * Describes the return value for revert_submissions_to_draft
1438 * @return external_single_structure
1441 public static function revert_submissions_to_draft_returns() {
1442 return new external_warnings();
1446 * Describes the parameters for unlock_submissions
1447 * @return external_external_function_parameters
1450 public static function unlock_submissions_parameters() {
1451 return new external_function_parameters(
1453 'assignmentid' => new external_value(PARAM_INT, 'The assignment id to operate on'),
1454 'userids' => new external_multiple_structure(
1455 new external_value(PARAM_INT, 'user id'),
1456 '1 or more user ids',
1463 * Locks (prevent updates to) submissions in this assignment.
1465 * @param int $assignmentid The id of the assignment
1466 * @param array $userids Array of user ids to lock
1467 * @return array of warnings for each submission that could not be locked.
1470 public static function unlock_submissions($assignmentid, $userids) {
1473 $params = self::validate_parameters(self::unlock_submissions_parameters(),
1474 array('assignmentid' => $assignmentid,
1475 'userids' => $userids));
1477 list($assignment, $course, $cm, $context) = self::validate_assign($params['assignmentid']);
1479 $warnings = array();
1480 foreach ($params['userids'] as $userid) {
1481 if (!$assignment->unlock_submission($userid)) {
1482 $detail = 'User id: ' . $userid . ', Assignment id: ' . $params['assignmentid'];
1483 $warnings[] = self::generate_warning($params['assignmentid'],
1493 * Describes the return value for unlock_submissions
1495 * @return external_single_structure
1498 public static function unlock_submissions_returns() {
1499 return new external_warnings();
1503 * Describes the parameters for submit_grading_form webservice.
1504 * @return external_external_function_parameters
1507 public static function submit_grading_form_parameters() {
1508 return new external_function_parameters(
1510 'assignmentid' => new external_value(PARAM_INT, 'The assignment id to operate on'),
1511 'userid' => new external_value(PARAM_INT, 'The user id the submission belongs to'),
1512 'jsonformdata' => new external_value(PARAM_RAW, 'The data from the grading form, encoded as a json array')
1518 * Submit the logged in users assignment for grading.
1520 * @param int $assignmentid The id of the assignment
1521 * @param int $userid The id of the user the submission belongs to.
1522 * @param string $jsonformdata The data from the form, encoded as a json array.
1523 * @return array of warnings to indicate any errors.
1526 public static function submit_grading_form($assignmentid, $userid, $jsonformdata) {
1529 require_once($CFG->dirroot . '/mod/assign/locallib.php');
1530 require_once($CFG->dirroot . '/mod/assign/gradeform.php');
1532 $params = self::validate_parameters(self::submit_grading_form_parameters(),
1534 'assignmentid' => $assignmentid,
1535 'userid' => $userid,
1536 'jsonformdata' => $jsonformdata
1539 list($assignment, $course, $cm, $context) = self::validate_assign($params['assignmentid']);
1541 $serialiseddata = json_decode($params['jsonformdata']);
1544 parse_str($serialiseddata, $data);
1546 $warnings = array();
1549 'userid' => $params['userid'],
1550 'attemptnumber' => $data['attemptnumber'],
1552 'gradingpanel' => true
1555 $customdata = (object) $data;
1556 $formparams = array($assignment, $customdata, $options);
1558 // Data is injected into the form by the last param for the constructor.
1559 $mform = new mod_assign_grade_form(null, $formparams, 'post', '', null, true, $data);
1560 $validateddata = $mform->get_data();
1562 if ($validateddata) {
1563 $assignment->save_grade($params['userid'], $validateddata);
1565 $warnings[] = self::generate_warning($params['assignmentid'],
1566 'couldnotsavegrade',
1567 'Form validation failed.');
1575 * Describes the return for submit_grading_form
1576 * @return external_external_function_parameters
1579 public static function submit_grading_form_returns() {
1580 return new external_warnings();
1584 * Describes the parameters for submit_for_grading
1585 * @return external_external_function_parameters
1588 public static function submit_for_grading_parameters() {
1589 return new external_function_parameters(
1591 'assignmentid' => new external_value(PARAM_INT, 'The assignment id to operate on'),
1592 'acceptsubmissionstatement' => new external_value(PARAM_BOOL, 'Accept the assignment submission statement')
1598 * Submit the logged in users assignment for grading.
1600 * @param int $assignmentid The id of the assignment
1601 * @return array of warnings to indicate any errors.
1604 public static function submit_for_grading($assignmentid, $acceptsubmissionstatement) {
1607 $params = self::validate_parameters(self::submit_for_grading_parameters(),
1608 array('assignmentid' => $assignmentid,
1609 'acceptsubmissionstatement' => $acceptsubmissionstatement));
1611 list($assignment, $course, $cm, $context) = self::validate_assign($params['assignmentid']);
1613 $warnings = array();
1614 $data = new stdClass();
1615 $data->submissionstatement = $params['acceptsubmissionstatement'];
1618 if (!$assignment->submit_for_grading($data, $notices)) {
1619 $detail = 'User id: ' . $USER->id . ', Assignment id: ' . $params['assignmentid'] . ' Notices:' . implode(', ', $notices);
1620 $warnings[] = self::generate_warning($params['assignmentid'],
1621 'couldnotsubmitforgrading',
1629 * Describes the return value for submit_for_grading
1631 * @return external_single_structure
1634 public static function submit_for_grading_returns() {
1635 return new external_warnings();
1639 * Describes the parameters for save_user_extensions
1640 * @return external_external_function_parameters
1643 public static function save_user_extensions_parameters() {
1644 return new external_function_parameters(
1646 'assignmentid' => new external_value(PARAM_INT, 'The assignment id to operate on'),
1647 'userids' => new external_multiple_structure(
1648 new external_value(PARAM_INT, 'user id'),
1649 '1 or more user ids',
1651 'dates' => new external_multiple_structure(
1652 new external_value(PARAM_INT, 'dates'),
1653 '1 or more extension dates (timestamp)',
1660 * Grant extension dates to students for an assignment.
1662 * @param int $assignmentid The id of the assignment
1663 * @param array $userids Array of user ids to grant extensions to
1664 * @param array $dates Array of extension dates
1665 * @return array of warnings for each extension date that could not be granted
1668 public static function save_user_extensions($assignmentid, $userids, $dates) {
1671 $params = self::validate_parameters(self::save_user_extensions_parameters(),
1672 array('assignmentid' => $assignmentid,
1673 'userids' => $userids,
1674 'dates' => $dates));
1676 if (count($params['userids']) != count($params['dates'])) {
1677 $detail = 'Length of userids and dates parameters differ.';
1678 $warnings[] = self::generate_warning($params['assignmentid'],
1679 'invalidparameters',
1685 list($assignment, $course, $cm, $context) = self::validate_assign($params['assignmentid']);
1687 $warnings = array();
1688 foreach ($params['userids'] as $idx => $userid) {
1689 $duedate = $params['dates'][$idx];
1690 if (!$assignment->save_user_extension($userid, $duedate)) {
1691 $detail = 'User id: ' . $userid . ', Assignment id: ' . $params['assignmentid'] . ', Extension date: ' . $duedate;
1692 $warnings[] = self::generate_warning($params['assignmentid'],
1693 'couldnotgrantextensions',
1702 * Describes the return value for save_user_extensions
1704 * @return external_single_structure
1707 public static function save_user_extensions_returns() {
1708 return new external_warnings();
1712 * Describes the parameters for reveal_identities
1713 * @return external_external_function_parameters
1716 public static function reveal_identities_parameters() {
1717 return new external_function_parameters(
1719 'assignmentid' => new external_value(PARAM_INT, 'The assignment id to operate on')
1725 * Reveal the identities of anonymous students to markers for a single assignment.
1727 * @param int $assignmentid The id of the assignment
1728 * @return array of warnings to indicate any errors.
1731 public static function reveal_identities($assignmentid) {
1734 $params = self::validate_parameters(self::reveal_identities_parameters(),
1735 array('assignmentid' => $assignmentid));
1737 list($assignment, $course, $cm, $context) = self::validate_assign($params['assignmentid']);
1739 $warnings = array();
1740 if (!$assignment->reveal_identities()) {
1741 $detail = 'User id: ' . $USER->id . ', Assignment id: ' . $params['assignmentid'];
1742 $warnings[] = self::generate_warning($params['assignmentid'],
1743 'couldnotrevealidentities',
1751 * Describes the return value for reveal_identities
1753 * @return external_single_structure
1756 public static function reveal_identities_returns() {
1757 return new external_warnings();
1761 * Describes the parameters for save_submission
1762 * @return external_external_function_parameters
1765 public static function save_submission_parameters() {
1767 $instance = new assign(null, null, null);
1768 $pluginsubmissionparams = array();
1770 foreach ($instance->get_submission_plugins() as $plugin) {
1771 if ($plugin->is_visible()) {
1772 $pluginparams = $plugin->get_external_parameters();
1773 if (!empty($pluginparams)) {
1774 $pluginsubmissionparams = array_merge($pluginsubmissionparams, $pluginparams);
1779 return new external_function_parameters(
1781 'assignmentid' => new external_value(PARAM_INT, 'The assignment id to operate on'),
1782 'plugindata' => new external_single_structure(
1783 $pluginsubmissionparams
1790 * Save a student submission for a single assignment
1792 * @param int $assignmentid The id of the assignment
1793 * @param array $plugindata - The submitted data for plugins
1794 * @return array of warnings to indicate any errors
1797 public static function save_submission($assignmentid, $plugindata) {
1800 $params = self::validate_parameters(self::save_submission_parameters(),
1801 array('assignmentid' => $assignmentid,
1802 'plugindata' => $plugindata));
1804 list($assignment, $course, $cm, $context) = self::validate_assign($params['assignmentid']);
1808 if (!$assignment->submissions_open($USER->id)) {
1809 $notices[] = get_string('duedatereached', 'assign');
1811 $submissiondata = (object)$params['plugindata'];
1812 $assignment->save_submission($submissiondata, $notices);
1815 $warnings = array();
1816 foreach ($notices as $notice) {
1817 $warnings[] = self::generate_warning($params['assignmentid'],
1818 'couldnotsavesubmission',
1826 * Describes the return value for save_submission
1828 * @return external_single_structure
1831 public static function save_submission_returns() {
1832 return new external_warnings();
1836 * Describes the parameters for save_grade
1837 * @return external_external_function_parameters
1840 public static function save_grade_parameters() {
1842 require_once("$CFG->dirroot/grade/grading/lib.php");
1843 $instance = new assign(null, null, null);
1844 $pluginfeedbackparams = array();
1846 foreach ($instance->get_feedback_plugins() as $plugin) {
1847 if ($plugin->is_visible()) {
1848 $pluginparams = $plugin->get_external_parameters();
1849 if (!empty($pluginparams)) {
1850 $pluginfeedbackparams = array_merge($pluginfeedbackparams, $pluginparams);
1855 $advancedgradingdata = array();
1856 $methods = array_keys(grading_manager::available_methods(false));
1857 foreach ($methods as $method) {
1858 require_once($CFG->dirroot.'/grade/grading/form/'.$method.'/lib.php');
1859 $details = call_user_func('gradingform_'.$method.'_controller::get_external_instance_filling_details');
1860 if (!empty($details)) {
1862 foreach ($details as $key => $value) {
1863 $value->required = VALUE_OPTIONAL;
1864 unset($value->content->keys['id']);
1865 $items[$key] = new external_multiple_structure (new external_single_structure(
1867 'criterionid' => new external_value(PARAM_INT, 'criterion id'),
1868 'fillings' => $value
1872 $advancedgradingdata[$method] = new external_single_structure($items, 'items', VALUE_OPTIONAL);
1876 return new external_function_parameters(
1878 'assignmentid' => new external_value(PARAM_INT, 'The assignment id to operate on'),
1879 'userid' => new external_value(PARAM_INT, 'The student id to operate on'),
1880 'grade' => new external_value(PARAM_FLOAT, 'The new grade for this user. Ignored if advanced grading used'),
1881 'attemptnumber' => new external_value(PARAM_INT, 'The attempt number (-1 means latest attempt)'),
1882 'addattempt' => new external_value(PARAM_BOOL, 'Allow another attempt if the attempt reopen method is manual'),
1883 'workflowstate' => new external_value(PARAM_ALPHA, 'The next marking workflow state'),
1884 'applytoall' => new external_value(PARAM_BOOL, 'If true, this grade will be applied ' .
1886 'of the group (for group assignments).'),
1887 'plugindata' => new external_single_structure($pluginfeedbackparams, 'plugin data', VALUE_DEFAULT, array()),
1888 'advancedgradingdata' => new external_single_structure($advancedgradingdata, 'advanced grading data',
1889 VALUE_DEFAULT, array())
1895 * Save a student grade for a single assignment.
1897 * @param int $assignmentid The id of the assignment
1898 * @param int $userid The id of the user
1899 * @param float $grade The grade (ignored if the assignment uses advanced grading)
1900 * @param int $attemptnumber The attempt number
1901 * @param bool $addattempt Allow another attempt
1902 * @param string $workflowstate New workflow state
1903 * @param bool $applytoall Apply the grade to all members of the group
1904 * @param array $plugindata Custom data used by plugins
1905 * @param array $advancedgradingdata Advanced grading data
1909 public static function save_grade($assignmentid,
1916 $plugindata = array(),
1917 $advancedgradingdata = array()) {
1920 $params = self::validate_parameters(self::save_grade_parameters(),
1921 array('assignmentid' => $assignmentid,
1922 'userid' => $userid,
1924 'attemptnumber' => $attemptnumber,
1925 'workflowstate' => $workflowstate,
1926 'addattempt' => $addattempt,
1927 'applytoall' => $applytoall,
1928 'plugindata' => $plugindata,
1929 'advancedgradingdata' => $advancedgradingdata));
1931 list($assignment, $course, $cm, $context) = self::validate_assign($params['assignmentid']);
1933 $gradedata = (object)$params['plugindata'];
1935 $gradedata->addattempt = $params['addattempt'];
1936 $gradedata->attemptnumber = $params['attemptnumber'];
1937 $gradedata->workflowstate = $params['workflowstate'];
1938 $gradedata->applytoall = $params['applytoall'];
1939 $gradedata->grade = $params['grade'];
1941 if (!empty($params['advancedgradingdata'])) {
1942 $advancedgrading = array();
1943 $criteria = reset($params['advancedgradingdata']);
1944 foreach ($criteria as $key => $criterion) {
1946 foreach ($criterion as $value) {
1947 foreach ($value['fillings'] as $filling) {
1948 $details[$value['criterionid']] = $filling;
1951 $advancedgrading[$key] = $details;
1953 $gradedata->advancedgrading = $advancedgrading;
1956 $assignment->save_grade($params['userid'], $gradedata);
1962 * Describes the return value for save_grade
1964 * @return external_single_structure
1967 public static function save_grade_returns() {
1972 * Describes the parameters for save_grades
1973 * @return external_external_function_parameters
1976 public static function save_grades_parameters() {
1978 require_once("$CFG->dirroot/grade/grading/lib.php");
1979 $instance = new assign(null, null, null);
1980 $pluginfeedbackparams = array();
1982 foreach ($instance->get_feedback_plugins() as $plugin) {
1983 if ($plugin->is_visible()) {
1984 $pluginparams = $plugin->get_external_parameters();
1985 if (!empty($pluginparams)) {
1986 $pluginfeedbackparams = array_merge($pluginfeedbackparams, $pluginparams);
1991 $advancedgradingdata = array();
1992 $methods = array_keys(grading_manager::available_methods(false));
1993 foreach ($methods as $method) {
1994 require_once($CFG->dirroot.'/grade/grading/form/'.$method.'/lib.php');
1995 $details = call_user_func('gradingform_'.$method.'_controller::get_external_instance_filling_details');
1996 if (!empty($details)) {
1998 foreach ($details as $key => $value) {
1999 $value->required = VALUE_OPTIONAL;
2000 unset($value->content->keys['id']);
2001 $items[$key] = new external_multiple_structure (new external_single_structure(
2003 'criterionid' => new external_value(PARAM_INT, 'criterion id'),
2004 'fillings' => $value
2008 $advancedgradingdata[$method] = new external_single_structure($items, 'items', VALUE_OPTIONAL);
2012 return new external_function_parameters(
2014 'assignmentid' => new external_value(PARAM_INT, 'The assignment id to operate on'),
2015 'applytoall' => new external_value(PARAM_BOOL, 'If true, this grade will be applied ' .
2017 'of the group (for group assignments).'),
2018 'grades' => new external_multiple_structure(
2019 new external_single_structure(
2021 'userid' => new external_value(PARAM_INT, 'The student id to operate on'),
2022 'grade' => new external_value(PARAM_FLOAT, 'The new grade for this user. '.
2023 'Ignored if advanced grading used'),
2024 'attemptnumber' => new external_value(PARAM_INT, 'The attempt number (-1 means latest attempt)'),
2025 'addattempt' => new external_value(PARAM_BOOL, 'Allow another attempt if manual attempt reopen method'),
2026 'workflowstate' => new external_value(PARAM_ALPHA, 'The next marking workflow state'),
2027 'plugindata' => new external_single_structure($pluginfeedbackparams, 'plugin data',
2028 VALUE_DEFAULT, array()),
2029 'advancedgradingdata' => new external_single_structure($advancedgradingdata, 'advanced grading data',
2030 VALUE_DEFAULT, array())
2039 * Save multiple student grades for a single assignment.
2041 * @param int $assignmentid The id of the assignment
2042 * @param boolean $applytoall If set to true and this is a team assignment,
2043 * apply the grade to all members of the group
2044 * @param array $grades grade data for one or more students that includes
2045 * userid - The id of the student being graded
2046 * grade - The grade (ignored if the assignment uses advanced grading)
2047 * attemptnumber - The attempt number
2048 * addattempt - Allow another attempt
2049 * workflowstate - New workflow state
2050 * plugindata - Custom data used by plugins
2051 * advancedgradingdata - Optional Advanced grading data
2052 * @throws invalid_parameter_exception if multiple grades are supplied for
2053 * a team assignment that has $applytoall set to true
2057 public static function save_grades($assignmentid, $applytoall = false, $grades) {
2060 $params = self::validate_parameters(self::save_grades_parameters(),
2061 array('assignmentid' => $assignmentid,
2062 'applytoall' => $applytoall,
2063 'grades' => $grades));
2065 list($assignment, $course, $cm, $context) = self::validate_assign($params['assignmentid']);
2067 if ($assignment->get_instance()->teamsubmission && $params['applytoall']) {
2068 // Check that only 1 user per submission group is provided.
2069 $groupids = array();
2070 foreach ($params['grades'] as $gradeinfo) {
2071 $group = $assignment->get_submission_group($gradeinfo['userid']);
2072 if (in_array($group->id, $groupids)) {
2073 throw new invalid_parameter_exception('Multiple grades for the same team have been supplied '
2074 .' this is not permitted when the applytoall flag is set');
2076 $groupids[] = $group->id;
2081 foreach ($params['grades'] as $gradeinfo) {
2082 $gradedata = (object)$gradeinfo['plugindata'];
2083 $gradedata->addattempt = $gradeinfo['addattempt'];
2084 $gradedata->attemptnumber = $gradeinfo['attemptnumber'];
2085 $gradedata->workflowstate = $gradeinfo['workflowstate'];
2086 $gradedata->applytoall = $params['applytoall'];
2087 $gradedata->grade = $gradeinfo['grade'];
2089 if (!empty($gradeinfo['advancedgradingdata'])) {
2090 $advancedgrading = array();
2091 $criteria = reset($gradeinfo['advancedgradingdata']);
2092 foreach ($criteria as $key => $criterion) {
2094 foreach ($criterion as $value) {
2095 foreach ($value['fillings'] as $filling) {
2096 $details[$value['criterionid']] = $filling;
2099 $advancedgrading[$key] = $details;
2101 $gradedata->advancedgrading = $advancedgrading;
2103 $assignment->save_grade($gradeinfo['userid'], $gradedata);
2110 * Describes the return value for save_grades
2112 * @return external_single_structure
2115 public static function save_grades_returns() {
2120 * Describes the parameters for copy_previous_attempt
2121 * @return external_function_parameters
2124 public static function copy_previous_attempt_parameters() {
2125 return new external_function_parameters(
2127 'assignmentid' => new external_value(PARAM_INT, 'The assignment id to operate on'),
2133 * Copy a students previous attempt to a new attempt.
2135 * @param int $assignmentid
2136 * @return array of warnings to indicate any errors.
2139 public static function copy_previous_attempt($assignmentid) {
2141 $params = self::validate_parameters(self::copy_previous_attempt_parameters(),
2142 array('assignmentid' => $assignmentid));
2144 list($assignment, $course, $cm, $context) = self::validate_assign($params['assignmentid']);
2148 $assignment->copy_previous_attempt($notices);
2150 $warnings = array();
2151 foreach ($notices as $notice) {
2152 $warnings[] = self::generate_warning($assignmentid,
2153 'couldnotcopyprevioussubmission',
2161 * Describes the return value for save_submission
2163 * @return external_single_structure
2166 public static function copy_previous_attempt_returns() {
2167 return new external_warnings();
2171 * Returns description of method parameters
2173 * @return external_function_parameters
2176 public static function view_grading_table_parameters() {
2177 return new external_function_parameters(
2179 'assignid' => new external_value(PARAM_INT, 'assign instance id')
2185 * Trigger the grading_table_viewed event.
2187 * @param int $assignid the assign instance id
2188 * @return array of warnings and status result
2190 * @throws moodle_exception
2192 public static function view_grading_table($assignid) {
2194 $params = self::validate_parameters(self::view_grading_table_parameters(),
2196 'assignid' => $assignid
2198 $warnings = array();
2200 list($assign, $course, $cm, $context) = self::validate_assign($params['assignid']);
2202 $assign->require_view_grades();
2203 \mod_assign\event\grading_table_viewed::create_from_assign($assign)->trigger();
2206 $result['status'] = true;
2207 $result['warnings'] = $warnings;
2212 * Returns description of method result value
2214 * @return external_description
2217 public static function view_grading_table_returns() {
2218 return new external_single_structure(
2220 'status' => new external_value(PARAM_BOOL, 'status: true if success'),
2221 'warnings' => new external_warnings()
2227 * Describes the parameters for view_submission_status.
2229 * @return external_external_function_parameters
2232 public static function view_submission_status_parameters() {
2233 return new external_function_parameters (
2235 'assignid' => new external_value(PARAM_INT, 'assign instance id'),
2241 * Trigger the submission status viewed event.
2243 * @param int $assignid assign instance id
2244 * @return array of warnings and status result
2247 public static function view_submission_status($assignid) {
2249 $warnings = array();
2251 'assignid' => $assignid,
2253 $params = self::validate_parameters(self::view_submission_status_parameters(), $params);
2255 list($assign, $course, $cm, $context) = self::validate_assign($params['assignid']);
2257 \mod_assign\event\submission_status_viewed::create_from_assign($assign)->trigger();
2260 $result['status'] = true;
2261 $result['warnings'] = $warnings;
2266 * Describes the view_submission_status return value.
2268 * @return external_single_structure
2271 public static function view_submission_status_returns() {
2272 return new external_single_structure(
2274 'status' => new external_value(PARAM_BOOL, 'status: true if success'),
2275 'warnings' => new external_warnings(),
2281 * Describes the parameters for get_submission_status.
2283 * @return external_external_function_parameters
2286 public static function get_submission_status_parameters() {
2287 return new external_function_parameters (
2289 'assignid' => new external_value(PARAM_INT, 'assignment instance id'),
2290 'userid' => new external_value(PARAM_INT, 'user id (empty for current user)', VALUE_DEFAULT, 0),
2296 * Returns information about an assignment submission status for a given user.
2298 * @param int $assignid assignment instance id
2299 * @param int $userid user id (empty for current user)
2300 * @return array of warnings and grading, status, feedback and previous attempts information
2302 * @throws required_capability_exception
2304 public static function get_submission_status($assignid, $userid = 0) {
2307 $warnings = array();
2310 'assignid' => $assignid,
2311 'userid' => $userid,
2313 $params = self::validate_parameters(self::get_submission_status_parameters(), $params);
2315 list($assign, $course, $cm, $context) = self::validate_assign($params['assignid']);
2317 // Default value for userid.
2318 if (empty($params['userid'])) {
2319 $params['userid'] = $USER->id;
2321 $user = core_user::get_user($params['userid'], '*', MUST_EXIST);
2322 core_user::require_active_user($user);
2324 if (!$assign->can_view_submission($user->id)) {
2325 throw new required_capability_exception($context, 'mod/assign:viewgrades', 'nopermission', '');
2328 $gradingsummary = $lastattempt = $feedback = $previousattempts = null;
2330 // Get the renderable since it contais all the info we need.
2331 if ($assign->can_view_grades()) {
2332 $gradingsummary = $assign->get_assign_grading_summary_renderable();
2335 // Retrieve the rest of the renderable objects.
2336 if (has_capability('mod/assign:submit', $assign->get_context(), $user)) {
2337 $lastattempt = $assign->get_assign_submission_status_renderable($user, true);
2340 $feedback = $assign->get_assign_feedback_status_renderable($user);
2342 $previousattempts = $assign->get_assign_attempt_history_renderable($user);
2344 // Now, build the result.
2347 // First of all, grading summary, this is suitable for teachers/managers.
2348 if ($gradingsummary) {
2349 $result['gradingsummary'] = $gradingsummary;
2352 // Did we submit anything?
2354 $submissionplugins = $assign->get_submission_plugins();
2356 if (empty($lastattempt->submission)) {
2357 unset($lastattempt->submission);
2359 $lastattempt->submission->plugins = self::get_plugins_data($assign, $submissionplugins, $lastattempt->submission);
2362 if (empty($lastattempt->teamsubmission)) {
2363 unset($lastattempt->teamsubmission);
2365 $lastattempt->teamsubmission->plugins = self::get_plugins_data($assign, $submissionplugins,
2366 $lastattempt->teamsubmission);
2369 // We need to change the type of some of the structures retrieved from the renderable.
2370 if (!empty($lastattempt->submissiongroup)) {
2371 $lastattempt->submissiongroup = $lastattempt->submissiongroup->id;
2373 unset($lastattempt->submissiongroup);
2376 if (!empty($lastattempt->usergroups)) {
2377 $lastattempt->usergroups = array_keys($lastattempt->usergroups);
2379 // We cannot use array_keys here.
2380 if (!empty($lastattempt->submissiongroupmemberswhoneedtosubmit)) {
2381 $lastattempt->submissiongroupmemberswhoneedtosubmit = array_map(
2385 $lastattempt->submissiongroupmemberswhoneedtosubmit);
2388 $result['lastattempt'] = $lastattempt;
2391 // The feedback for our latest submission.
2393 if ($feedback->grade) {
2394 $feedbackplugins = $assign->get_feedback_plugins();
2395 $feedback->plugins = self::get_plugins_data($assign, $feedbackplugins, $feedback->grade);
2397 unset($feedback->plugins);
2398 unset($feedback->grade);
2401 $result['feedback'] = $feedback;
2404 // Retrieve only previous attempts.
2405 if ($previousattempts and count($previousattempts->submissions) > 1) {
2406 // Don't show the last one because it is the current submission.
2407 array_pop($previousattempts->submissions);
2409 // Show newest to oldest.
2410 $previousattempts->submissions = array_reverse($previousattempts->submissions);
2412 foreach ($previousattempts->submissions as $i => $submission) {
2416 foreach ($previousattempts->grades as $onegrade) {
2417 if ($onegrade->attemptnumber == $submission->attemptnumber) {
2423 $attempt['attemptnumber'] = $submission->attemptnumber;
2426 $submission->plugins = self::get_plugins_data($assign, $previousattempts->submissionplugins, $submission);
2427 $attempt['submission'] = $submission;
2431 // From object to id.
2432 $grade->grader = $grade->grader->id;
2433 $feedbackplugins = self::get_plugins_data($assign, $previousattempts->feedbackplugins, $grade);
2435 $attempt['grade'] = $grade;
2436 $attempt['feedbackplugins'] = $feedbackplugins;
2438 $result['previousattempts'][] = $attempt;
2442 $result['warnings'] = $warnings;
2447 * Describes the get_submission_status return value.
2449 * @return external_single_structure
2452 public static function get_submission_status_returns() {
2453 return new external_single_structure(
2455 'gradingsummary' => new external_single_structure(
2457 'participantcount' => new external_value(PARAM_INT, 'Number of users who can submit.'),
2458 'submissiondraftscount' => new external_value(PARAM_INT, 'Number of submissions in draft status.'),
2459 'submissiondraftscount' => new external_value(PARAM_INT, 'Number of submissions in draft status.'),
2460 'submissionsenabled' => new external_value(PARAM_BOOL, 'Whether submissions are enabled or not.'),
2461 'submissionssubmittedcount' => new external_value(PARAM_INT, 'Number of submissions in submitted status.'),
2462 'submissionsneedgradingcount' => new external_value(PARAM_INT, 'Number of submissions that need grading.'),
2463 'warnofungroupedusers' => new external_value(PARAM_BOOL, 'Whether we need to warn people that there
2464 are users without groups.'),
2465 ), 'Grading information.', VALUE_OPTIONAL
2467 'lastattempt' => new external_single_structure(
2469 'submission' => self::get_submission_structure(VALUE_OPTIONAL),
2470 'teamsubmission' => self::get_submission_structure(VALUE_OPTIONAL),
2471 'submissiongroup' => new external_value(PARAM_INT, 'The submission group id (for group submissions only).',
2473 'submissiongroupmemberswhoneedtosubmit' => new external_multiple_structure(
2474 new external_value(PARAM_INT, 'USER id.'),
2475 'List of users who still need to submit (for group submissions only).',
2478 'submissionsenabled' => new external_value(PARAM_BOOL, 'Whether submissions are enabled or not.'),
2479 'locked' => new external_value(PARAM_BOOL, 'Whether new submissions are locked.'),
2480 'graded' => new external_value(PARAM_BOOL, 'Whether the submission is graded.'),
2481 'canedit' => new external_value(PARAM_BOOL, 'Whether the user can edit the current submission.'),
2482 'cansubmit' => new external_value(PARAM_BOOL, 'Whether the user can submit.'),
2483 'extensionduedate' => new external_value(PARAM_INT, 'Extension due date.'),
2484 'blindmarking' => new external_value(PARAM_BOOL, 'Whether blind marking is enabled.'),
2485 'gradingstatus' => new external_value(PARAM_ALPHANUMEXT, 'Grading status.'),
2486 'usergroups' => new external_multiple_structure(
2487 new external_value(PARAM_INT, 'Group id.'), 'User groups in the course.'
2489 ), 'Last attempt information.', VALUE_OPTIONAL
2491 'feedback' => new external_single_structure(
2493 'grade' => self::get_grade_structure(VALUE_OPTIONAL),
2494 'gradefordisplay' => new external_value(PARAM_RAW, 'Grade rendered into a format suitable for display.'),
2495 'gradeddate' => new external_value(PARAM_INT, 'The date the user was graded.'),
2496 'plugins' => new external_multiple_structure(self::get_plugin_structure(), 'Plugins info.', VALUE_OPTIONAL),
2497 ), 'Feedback for the last attempt.', VALUE_OPTIONAL
2499 'previousattempts' => new external_multiple_structure(
2500 new external_single_structure(
2502 'attemptnumber' => new external_value(PARAM_INT, 'Attempt number.'),
2503 'submission' => self::get_submission_structure(VALUE_OPTIONAL),
2504 'grade' => self::get_grade_structure(VALUE_OPTIONAL),
2505 'feedbackplugins' => new external_multiple_structure(self::get_plugin_structure(), 'Feedback info.',
2508 ), 'List all the previous attempts did by the user.', VALUE_OPTIONAL
2510 'warnings' => new external_warnings(),
2516 * Returns description of method parameters
2518 * @return external_function_parameters
2521 public static function list_participants_parameters() {
2522 return new external_function_parameters(
2524 'assignid' => new external_value(PARAM_INT, 'assign instance id'),
2525 'groupid' => new external_value(PARAM_INT, 'group id'),
2526 'filter' => new external_value(PARAM_RAW, 'search string to filter the results'),
2527 'skip' => new external_value(PARAM_INT, 'number of records to skip', VALUE_DEFAULT, 0),
2528 'limit' => new external_value(PARAM_INT, 'maximum number of records to return', VALUE_DEFAULT, 0),
2529 'onlyids' => new external_value(PARAM_BOOL, 'Do not return all user fields', VALUE_DEFAULT, false),
2535 * Retrieves the list of students to be graded for the assignment.
2537 * @param int $assignid the assign instance id
2538 * @param int $groupid the current group id
2539 * @param string $filter search string to filter the results.
2540 * @param int $skip Number of records to skip
2541 * @param int $limit Maximum number of records to return
2542 * @return array of warnings and status result
2544 * @throws moodle_exception
2546 public static function list_participants($assignid, $groupid, $filter, $skip, $limit) {
2548 require_once($CFG->dirroot . "/mod/assign/locallib.php");
2549 require_once($CFG->dirroot . "/user/lib.php");
2551 $params = self::validate_parameters(self::list_participants_parameters(),
2553 'assignid' => $assignid,
2554 'groupid' => $groupid,
2555 'filter' => $filter,
2559 $warnings = array();
2561 list($assign, $course, $cm, $context) = self::validate_assign($params['assignid']);
2563 require_capability('mod/assign:view', $context);
2565 $assign->require_view_grades();
2567 $participants = $assign->list_participants_with_filter_status_and_group($params['groupid']);
2571 foreach ($participants as $record) {
2572 // Preserve the fullname set by the assignment.
2573 $fullname = $record->fullname;
2574 $searchable = $fullname;
2576 if (empty($filter)) {
2579 $filter = core_text::strtolower($filter);
2580 $value = core_text::strtolower($searchable);
2581 if (is_string($value) && (core_text::strpos($value, $filter) !== false)) {
2587 if ($index <= $params['skip']) {
2590 if (($params['limit'] > 0) && (($index - $params['skip']) > $params['limit'])) {
2593 // Now we do the expensive lookup of user details because we completed the filtering.
2594 if (!$assign->is_blind_marking() && !$params['onlyids']) {
2595 $userdetails = user_get_user_details($record, $course);
2597 $userdetails = array('id' => $record->id);
2599 $userdetails['fullname'] = $fullname;
2600 $userdetails['submitted'] = $record->submitted;
2601 $userdetails['requiregrading'] = $record->requiregrading;
2602 if (!empty($record->groupid)) {
2603 $userdetails['groupid'] = $record->groupid;
2605 if (!empty($record->groupname)) {
2606 $userdetails['groupname'] = $record->groupname;
2609 $result[] = $userdetails;
2616 * Returns the description of the results of the mod_assign_external::list_participants() method.
2618 * @return external_description
2621 public static function list_participants_returns() {
2622 // Get user description.
2623 $userdesc = core_user_external::user_description();
2624 // List unneeded properties.
2625 $unneededproperties = [
2626 'auth', 'confirmed', 'lang', 'calendartype', 'theme', 'timezone', 'mailformat'
2628 // Remove unneeded properties for consistency with the previous version.
2629 foreach ($unneededproperties as $prop) {
2630 unset($userdesc->keys[$prop]);
2633 // Override property attributes for consistency with the previous version.
2634 $userdesc->keys['fullname']->type = PARAM_NOTAGS;
2635 $userdesc->keys['profileimageurlsmall']->required = VALUE_OPTIONAL;
2636 $userdesc->keys['profileimageurl']->required = VALUE_OPTIONAL;
2637 $userdesc->keys['email']->desc = 'Email address';
2638 $userdesc->keys['email']->desc = 'Email address';
2639 $userdesc->keys['idnumber']->desc = 'The idnumber of the user';
2641 // Define other keys.
2643 'groups' => new external_multiple_structure(
2644 new external_single_structure(
2646 'id' => new external_value(PARAM_INT, 'group id'),
2647 'name' => new external_value(PARAM_RAW, 'group name'),
2648 'description' => new external_value(PARAM_RAW, 'group description'),
2650 ), 'user groups', VALUE_OPTIONAL
2652 'roles' => new external_multiple_structure(
2653 new external_single_structure(
2655 'roleid' => new external_value(PARAM_INT, 'role id'),
2656 'name' => new external_value(PARAM_RAW, 'role name'),
2657 'shortname' => new external_value(PARAM_ALPHANUMEXT, 'role shortname'),
2658 'sortorder' => new external_value(PARAM_INT, 'role sortorder')
2660 ), 'user roles', VALUE_OPTIONAL
2662 'enrolledcourses' => new external_multiple_structure(
2663 new external_single_structure(
2665 'id' => new external_value(PARAM_INT, 'Id of the course'),
2666 'fullname' => new external_value(PARAM_RAW, 'Fullname of the course'),
2667 'shortname' => new external_value(PARAM_RAW, 'Shortname of the course')
2669 ), 'Courses where the user is enrolled - limited by which courses the user is able to see', VALUE_OPTIONAL
2671 'submitted' => new external_value(PARAM_BOOL, 'have they submitted their assignment'),
2672 'requiregrading' => new external_value(PARAM_BOOL, 'is their submission waiting for grading'),
2673 'groupid' => new external_value(PARAM_INT, 'for group assignments this is the group id', VALUE_OPTIONAL),
2674 'groupname' => new external_value(PARAM_NOTAGS, 'for group assignments this is the group name', VALUE_OPTIONAL),
2678 $userdesc->keys = array_merge($userdesc->keys, $otherkeys);
2679 return new external_multiple_structure($userdesc);
2683 * Returns description of method parameters
2685 * @return external_function_parameters
2688 public static function get_participant_parameters() {
2689 return new external_function_parameters(
2691 'assignid' => new external_value(PARAM_INT, 'assign instance id'),
2692 'userid' => new external_value(PARAM_INT, 'user id'),
2693 'embeduser' => new external_value(PARAM_BOOL, 'user id', VALUE_DEFAULT, false),
2699 * Get the user participating in the given assignment. An error with code 'usernotincourse'
2700 * is thrown is the user isn't a participant of the given assignment.
2702 * @param int $assignid the assign instance id
2703 * @param int $userid the user id
2704 * @param bool $embeduser return user details (only applicable if not blind marking)
2705 * @return array of warnings and status result
2707 * @throws moodle_exception
2709 public static function get_participant($assignid, $userid, $embeduser) {
2711 require_once($CFG->dirroot . "/mod/assign/locallib.php");
2712 require_once($CFG->dirroot . "/user/lib.php");
2714 $params = self::validate_parameters(self::get_participant_parameters(), array(
2715 'assignid' => $assignid,
2716 'userid' => $userid,
2717 'embeduser' => $embeduser
2720 list($assign, $course, $cm, $context) = self::validate_assign($params['assignid']);
2721 $assign->require_view_grades();
2723 $participant = $assign->get_participant($params['userid']);
2724 if (!$participant) {
2725 // No participant found so we can return early.
2726 throw new moodle_exception('usernotincourse');
2730 'id' => $participant->id,
2731 'fullname' => $participant->fullname,
2732 'submitted' => $participant->submitted,
2733 'requiregrading' => $participant->requiregrading,
2734 'blindmarking' => $assign->is_blind_marking(),
2737 if (!empty($participant->groupid)) {
2738 $return['groupid'] = $participant->groupid;
2740 if (!empty($participant->groupname)) {
2741 $return['groupname'] = $participant->groupname;
2744 // Skip the expensive lookup of user detail if we're blind marking or the caller
2745 // hasn't asked for user details to be embedded.
2746 if (!$assign->is_blind_marking() && $embeduser) {
2747 $return['user'] = user_get_user_details($participant, $course);
2754 * Returns description of method result value
2756 * @return external_description
2759 public static function get_participant_returns() {
2760 $userdescription = core_user_external::user_description();
2761 $userdescription->default = [];
2762 $userdescription->required = VALUE_OPTIONAL;
2764 return new external_single_structure(array(
2765 'id' => new external_value(PARAM_INT, 'ID of the user'),
2766 'fullname' => new external_value(PARAM_NOTAGS, 'The fullname of the user'),
2767 'submitted' => new external_value(PARAM_BOOL, 'have they submitted their assignment'),
2768 'requiregrading' => new external_value(PARAM_BOOL, 'is their submission waiting for grading'),
2769 'blindmarking' => new external_value(PARAM_BOOL, 'is blind marking enabled for this assignment'),
2770 'groupid' => new external_value(PARAM_INT, 'for group assignments this is the group id', VALUE_OPTIONAL),
2771 'groupname' => new external_value(PARAM_NOTAGS, 'for group assignments this is the group name', VALUE_OPTIONAL),
2772 'user' => $userdescription,
2777 * Utility function for validating an assign.
2779 * @param int $assignid assign instance id
2780 * @return array array containing the assign, course, context and course module objects
2783 protected static function validate_assign($assignid) {
2786 // Request and permission validation.
2787 $assign = $DB->get_record('assign', array('id' => $assignid), 'id', MUST_EXIST);
2788 list($course, $cm) = get_course_and_cm_from_instance($assign, 'assign');
2790 $context = context_module::instance($cm->id);
2791 // Please, note that is not required to check mod/assign:view because is done by validate_context->require_login.
2792 self::validate_context($context);
2793 $assign = new assign($context, $cm, $course);
2795 return array($assign, $course, $cm, $context);
2799 * Describes the parameters for view_assign.
2801 * @return external_external_function_parameters
2804 public static function view_assign_parameters() {
2805 return new external_function_parameters (
2807 'assignid' => new external_value(PARAM_INT, 'assign instance id'),
2813 * Update the module completion status.
2815 * @param int $assignid assign instance id
2816 * @return array of warnings and status result
2819 public static function view_assign($assignid) {
2820 $warnings = array();
2822 'assignid' => $assignid,
2824 $params = self::validate_parameters(self::view_assign_parameters(), $params);
2826 list($assign, $course, $cm, $context) = self::validate_assign($params['assignid']);
2828 $assign->set_module_viewed();
2831 $result['status'] = true;
2832 $result['warnings'] = $warnings;
2837 * Describes the view_assign return value.
2839 * @return external_single_structure
2842 public static function view_assign_returns() {
2843 return new external_single_structure(
2845 'status' => new external_value(PARAM_BOOL, 'status: true if success'),
2846 'warnings' => new external_warnings(),