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