MDL-30174 Assignment : Only increment submission offset if the current assignment...
[moodle.git] / mod / assignment / lib.php
CommitLineData
256578f6 1<?PHP
2
3// This file is part of Moodle - http://moodle.org/
4//
5// Moodle is free software: you can redistribute it and/or modify
6// it under the terms of the GNU General Public License as published by
7// the Free Software Foundation, either version 3 of the License, or
8// (at your option) any later version.
9//
10// Moodle is distributed in the hope that it will be useful,
11// but WITHOUT ANY WARRANTY; without even the implied warranty of
12// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13// GNU General Public License for more details.
14//
15// You should have received a copy of the GNU General Public License
16// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
19002f9f 17
b0f2597e 18/**
19 * assignment_base is the base class for assignment types
20 *
21 * This class provides all the functionality for an assignment
256578f6 22 *
b2d5a79a 23 * @package mod-assignment
256578f6 24 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
25 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
b0f2597e 26 */
04eba58f 27
256578f6 28/** Include eventslib.php */
3b120e46 29require_once($CFG->libdir.'/eventslib.php');
256578f6 30/** Include formslib.php */
172dd12c 31require_once($CFG->libdir.'/formslib.php');
9b72d37e
SH
32/** Include calendar/lib.php */
33require_once($CFG->dirroot.'/calendar/lib.php');
3b120e46 34
256578f6 35/** ASSIGNMENT_COUNT_WORDS = 1 */
6b1564a8 36define('ASSIGNMENT_COUNT_WORDS', 1);
256578f6 37/** ASSIGNMENT_COUNT_LETTERS = 2 */
6b1564a8 38define('ASSIGNMENT_COUNT_LETTERS', 2);
d699cd1e 39
7af1e882 40/**
b0f2597e 41 * Standard base class for all assignment submodules (assignment types).
e7521559 42 *
b2d5a79a 43 * @package mod-assignment
256578f6 44 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
45 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
b0f2597e 46 */
47class assignment_base {
48
fdb797ad
RW
49 const FILTER_ALL = 0;
50 const FILTER_SUBMITTED = 1;
51 const FILTER_REQUIRE_GRADING = 2;
52
256578f6 53 /** @var object */
b0f2597e 54 var $cm;
256578f6 55 /** @var object */
b0f2597e 56 var $course;
8ebbb06a
SH
57 /** @var stdClass */
58 var $coursecontext;
256578f6 59 /** @var object */
b0f2597e 60 var $assignment;
256578f6 61 /** @var string */
7af1e882 62 var $strassignment;
256578f6 63 /** @var string */
7af1e882 64 var $strassignments;
256578f6 65 /** @var string */
7af1e882 66 var $strsubmissions;
256578f6 67 /** @var string */
7af1e882 68 var $strlastmodified;
256578f6 69 /** @var string */
7af1e882 70 var $pagetitle;
256578f6 71 /** @var bool */
7af1e882 72 var $usehtmleditor;
256578f6 73 /**
74 * @todo document this var
75 */
7af1e882 76 var $defaultformat;
256578f6 77 /**
78 * @todo document this var
79 */
55b4d096 80 var $context;
256578f6 81 /** @var string */
0b5a80a1 82 var $type;
b0f2597e 83
84 /**
85 * Constructor for the base assignment class
86 *
87 * Constructor for the base assignment class.
88 * If cmid is set create the cm, course, assignment objects.
7af1e882 89 * If the assignment is hidden and the user is not a teacher then
90 * this prints a page header and notice.
b0f2597e 91 *
256578f6 92 * @global object
93 * @global object
94 * @param int $cmid the current course module id - not set for new assignments
95 * @param object $assignment usually null, but if we have it we pass it to save db access
96 * @param object $cm usually null, but if we have it we pass it to save db access
97 * @param object $course usually null, but if we have it we pass it to save db access
b0f2597e 98 */
7bddd4b7 99 function assignment_base($cmid='staticonly', $assignment=NULL, $cm=NULL, $course=NULL) {
5053f00f 100 global $COURSE, $DB;
dd97c328 101
7bddd4b7 102 if ($cmid == 'staticonly') {
103 //use static functions only!
104 return;
105 }
b0f2597e 106
107 global $CFG;
108
7bddd4b7 109 if ($cm) {
110 $this->cm = $cm;
111 } else if (! $this->cm = get_coursemodule_from_id('assignment', $cmid)) {
a939f681 112 print_error('invalidcoursemodule');
7bddd4b7 113 }
04eba58f 114
dd97c328 115 $this->context = get_context_instance(CONTEXT_MODULE, $this->cm->id);
55b4d096 116
7bddd4b7 117 if ($course) {
118 $this->course = $course;
dd97c328 119 } else if ($this->cm->course == $COURSE->id) {
120 $this->course = $COURSE;
5053f00f 121 } else if (! $this->course = $DB->get_record('course', array('id'=>$this->cm->course))) {
a939f681 122 print_error('invalidid', 'assignment');
7bddd4b7 123 }
8ebbb06a 124 $this->coursecontext = get_context_instance(CONTEXT_COURSE, $this->course->id);
eb38d45b 125 $courseshortname = format_text($this->course->shortname, true, array('context' => $this->coursecontext));
04eba58f 126
7bddd4b7 127 if ($assignment) {
128 $this->assignment = $assignment;
5053f00f 129 } else if (! $this->assignment = $DB->get_record('assignment', array('id'=>$this->cm->instance))) {
a939f681 130 print_error('invalidid', 'assignment');
7bddd4b7 131 }
132
3811c1d4 133 $this->assignment->cmidnumber = $this->cm->idnumber; // compatibility with modedit assignment obj
b5ebd096 134 $this->assignment->courseid = $this->course->id; // compatibility with modedit assignment obj
e6a4906b 135
7bddd4b7 136 $this->strassignment = get_string('modulename', 'assignment');
137 $this->strassignments = get_string('modulenameplural', 'assignment');
138 $this->strsubmissions = get_string('submissions', 'assignment');
139 $this->strlastmodified = get_string('lastmodified');
8ebbb06a 140 $this->pagetitle = strip_tags($courseshortname.': '.$this->strassignment.': '.format_string($this->assignment->name, true, array('context' => $this->context)));
7bddd4b7 141
f36cbf1d 142 // visibility handled by require_login() with $cm parameter
143 // get current group only when really needed
e6a4906b 144
73097f07 145 /// Set up things for a HTML editor if it's needed
20e5da7d 146 $this->defaultformat = editors_get_preferred_format();
e6a4906b 147 }
148
7af1e882 149 /**
150 * Display the assignment, used by view.php
151 *
152 * This in turn calls the methods producing individual parts of the page
b0f2597e 153 */
de75c481 154 function view() {
45fa3412 155
dabfd0ed 156 $context = get_context_instance(CONTEXT_MODULE,$this->cm->id);
0468976c 157 require_capability('mod/assignment:view', $context);
45fa3412 158
159 add_to_log($this->course->id, "assignment", "view", "view.php?id={$this->cm->id}",
b0f2597e 160 $this->assignment->id, $this->cm->id);
04eba58f 161
73097f07 162 $this->view_header();
04eba58f 163
f77cfb73 164 $this->view_intro();
04eba58f 165
f77cfb73 166 $this->view_dates();
04eba58f 167
b0f2597e 168 $this->view_feedback();
169
f77cfb73 170 $this->view_footer();
36eb856f 171 }
172
7af1e882 173 /**
174 * Display the header and top of a page
175 *
176 * (this doesn't change much for assignment types)
177 * This is used by the view() method to print the header of view.php but
178 * it can be used on other pages in which case the string to denote the
179 * page in the navigation trail should be passed as an argument
180 *
256578f6 181 * @global object
182 * @param string $subpage Description of subpage to be used in navigation trail
73097f07 183 */
184 function view_header($subpage='') {
83a7f058 185 global $CFG, $PAGE, $OUTPUT;
45fa3412 186
73097f07 187 if ($subpage) {
83a7f058 188 $PAGE->navbar->add($subpage);
73097f07 189 }
45fa3412 190
83a7f058 191 $PAGE->set_title($this->pagetitle);
192 $PAGE->set_heading($this->course->fullname);
83a7f058 193
194 echo $OUTPUT->header();
73097f07 195
f1035deb 196 groups_print_activity_menu($this->cm, $CFG->wwwroot . '/mod/assignment/view.php?id=' . $this->cm->id);
45fa3412 197
73097f07 198 echo '<div class="reportlink">'.$this->submittedlink().'</div>';
7bddd4b7 199 echo '<div class="clearer"></div>';
73097f07 200 }
201
202
7af1e882 203 /**
f77cfb73 204 * Display the assignment intro
7af1e882 205 *
206 * This will most likely be extended by assignment type plug-ins
207 * The default implementation prints the assignment description in a box
f77cfb73 208 */
209 function view_intro() {
3a003ead 210 global $OUTPUT;
211 echo $OUTPUT->box_start('generalbox boxaligncenter', 'intro');
dc5c2bd9 212 echo format_module_intro('assignment', $this->assignment, $this->cm->id);
3a003ead 213 echo $OUTPUT->box_end();
bce59524 214 plagiarism_print_disclosure($this->cm->id);
f77cfb73 215 }
216
7af1e882 217 /**
f77cfb73 218 * Display the assignment dates
7af1e882 219 *
220 * Prints the assignment start and end dates in a box.
221 * This will be suitable for most assignment types
f77cfb73 222 */
223 function view_dates() {
3a003ead 224 global $OUTPUT;
f77cfb73 225 if (!$this->assignment->timeavailable && !$this->assignment->timedue) {
226 return;
227 }
228
3a003ead 229 echo $OUTPUT->box_start('generalbox boxaligncenter', 'dates');
f77cfb73 230 echo '<table>';
231 if ($this->assignment->timeavailable) {
232 echo '<tr><td class="c0">'.get_string('availabledate','assignment').':</td>';
233 echo ' <td class="c1">'.userdate($this->assignment->timeavailable).'</td></tr>';
234 }
235 if ($this->assignment->timedue) {
236 echo '<tr><td class="c0">'.get_string('duedate','assignment').':</td>';
237 echo ' <td class="c1">'.userdate($this->assignment->timedue).'</td></tr>';
238 }
239 echo '</table>';
3a003ead 240 echo $OUTPUT->box_end();
f77cfb73 241 }
242
243
7af1e882 244 /**
245 * Display the bottom and footer of a page
246 *
247 * This default method just prints the footer.
248 * This will be suitable for most assignment types
73097f07 249 */
250 function view_footer() {
256d2850 251 global $OUTPUT;
252 echo $OUTPUT->footer();
73097f07 253 }
254
7af1e882 255 /**
256 * Display the feedback to the student
257 *
258 * This default method prints the teacher picture and name, date when marked,
ea6432fe 259 * grade and teacher submissioncomment.
156d6f48
MG
260 * If advanced grading is used the method render_grade from the
261 * advanced grading controller is called to display the grade.
7af1e882 262 *
256578f6 263 * @global object
264 * @global object
265 * @global object
266 * @param object $submission The submission object or NULL in which case it will be loaded
7af1e882 267 */
73097f07 268 function view_feedback($submission=NULL) {
36937f02 269 global $USER, $CFG, $DB, $OUTPUT, $PAGE;
5978010d 270 require_once($CFG->libdir.'/gradelib.php');
36937f02 271 require_once("$CFG->dirroot/grade/grading/lib.php");
e6a4906b 272
73097f07 273 if (!$submission) { /// Get submission for this assignment
156d6f48
MG
274 $userid = $USER->id;
275 $submission = $this->get_submission($userid);
276 } else {
277 $userid = $submission->userid;
70b2c772 278 }
c7bb34b6 279 // Check the user can submit
156d6f48 280 $canviewfeedback = ($userid == $USER->id && has_capability('mod/assignment:submit', $this->context, $USER->id, false));
91421f3e 281 // If not then check if the user still has the view cap and has a previous submission
156d6f48
MG
282 $canviewfeedback = $canviewfeedback || (!empty($submission) && $submission->userid == $USER->id && has_capability('mod/assignment:view', $this->context));
283 // Or if user can grade (is a teacher or admin)
284 $canviewfeedback = $canviewfeedback || has_capability('mod/assignment:grade', $this->context);
c7bb34b6 285
156d6f48
MG
286 if (!$canviewfeedback) {
287 // can not view or submit assignments -> no feedback
c7bb34b6
SH
288 return;
289 }
70b2c772 290
156d6f48 291 $grading_info = grade_get_grades($this->course->id, 'mod', 'assignment', $this->assignment->id, $userid);
5978010d 292 $item = $grading_info->items[0];
156d6f48 293 $grade = $item->grades[$userid];
5978010d 294
295 if ($grade->hidden or $grade->grade === false) { // hidden or error
296 return;
297 }
298
30d61820 299 if ($grade->grade === null and empty($grade->str_feedback)) { /// Nothing to show yet
70b2c772 300 return;
9c48354d 301 }
e6a4906b 302
ced5ee59 303 $graded_date = $grade->dategraded;
12dce253 304 $graded_by = $grade->usermodified;
e6a4906b 305
5978010d 306 /// We need the teacher info
5053f00f 307 if (!$teacher = $DB->get_record('user', array('id'=>$graded_by))) {
a939f681 308 print_error('cannotfindteacher');
12dce253 309 }
5978010d 310
b0f2597e 311 /// Print the feedback
867aeead 312 echo $OUTPUT->heading(get_string('feedbackfromteacher', 'assignment', fullname($teacher)));
6d4ecaec 313
b0f2597e 314 echo '<table cellspacing="0" class="feedback">';
315
316 echo '<tr>';
317 echo '<td class="left picture">';
5978010d 318 if ($teacher) {
812dbaf7 319 echo $OUTPUT->user_picture($teacher);
5978010d 320 }
b0f2597e 321 echo '</td>';
6d4ecaec 322 echo '<td class="topic">';
70b2c772 323 echo '<div class="from">';
5978010d 324 if ($teacher) {
325 echo '<div class="fullname">'.fullname($teacher).'</div>';
326 }
327 echo '<div class="time">'.userdate($graded_date).'</div>';
70b2c772 328 echo '</div>';
b0f2597e 329 echo '</td>';
330 echo '</tr>';
331
332 echo '<tr>';
333 echo '<td class="left side">&nbsp;</td>';
6d4ecaec 334 echo '<td class="content">';
3c2b3cb3 335 $gradestr = '<div class="grade">'. get_string("grade").': '.$grade->str_long_grade. '</div>';
36937f02 336 if (!empty($submission) && $controller = get_grading_manager($this->context, 'mod_assignment', 'submission')->get_active_controller()) {
9e2eca0f 337 $controller->set_grade_range(make_grades_menu($this->assignment->grade));
3c2b3cb3 338 echo $controller->render_grade($PAGE, $submission->id, $item, $gradestr, has_capability('mod/assignment:grade', $this->context));
36937f02 339 } else {
3c2b3cb3 340 echo $gradestr;
36937f02 341 }
5978010d 342 echo '<div class="clearer"></div>';
dcd338ff 343
6d4ecaec 344 echo '<div class="comment">';
5978010d 345 echo $grade->str_feedback;
6d4ecaec 346 echo '</div>';
b0f2597e 347 echo '</tr>';
348
8efd9deb
AB
349 if ($this->type == 'uploadsingle') { //@TODO: move to overload view_feedback method in the class or is uploadsingle merging into upload?
350 $responsefiles = $this->print_responsefiles($submission->userid, true);
351 if (!empty($responsefiles)) {
352 echo '<tr>';
353 echo '<td class="left side">&nbsp;</td>';
354 echo '<td class="content">';
355 echo $responsefiles;
356 echo '</tr>';
357 }
358 }
359
b0f2597e 360 echo '</table>';
e6a4906b 361 }
e6a4906b 362
45fa3412 363 /**
ba16713f 364 * Returns a link with info about the state of the assignment submissions
7af1e882 365 *
366 * This is used by view_header to put this link at the top right of the page.
367 * For teachers it gives the number of submitted assignments with a link
368 * For students it gives the time of their submission.
369 * This will be suitable for most assignment types.
256578f6 370 *
371 * @global object
372 * @global object
dd97c328 373 * @param bool $allgroup print all groups info if user can access all groups, suitable for index.php
7af1e882 374 * @return string
ba16713f 375 */
dd97c328 376 function submittedlink($allgroups=false) {
ba16713f 377 global $USER;
e1faf3b9 378 global $CFG;
ba16713f 379
380 $submitted = '';
e1faf3b9 381 $urlbase = "{$CFG->wwwroot}/mod/assignment/";
ba16713f 382
bbbf2d40 383 $context = get_context_instance(CONTEXT_MODULE,$this->cm->id);
1648afb2 384 if (has_capability('mod/assignment:grade', $context)) {
dd97c328 385 if ($allgroups and has_capability('moodle/site:accessallgroups', $context)) {
386 $group = 0;
ba16713f 387 } else {
f36cbf1d 388 $group = groups_get_activity_group($this->cm);
dd97c328 389 }
54c37fbd
RW
390 if ($this->type == 'offline') {
391 $submitted = '<a href="'.$urlbase.'submissions.php?id='.$this->cm->id.'">'.
392 get_string('viewfeedback', 'assignment').'</a>';
393 } else if ($count = $this->count_real_submissions($group)) {
e1faf3b9 394 $submitted = '<a href="'.$urlbase.'submissions.php?id='.$this->cm->id.'">'.
dd97c328 395 get_string('viewsubmissions', 'assignment', $count).'</a>';
396 } else {
e1faf3b9 397 $submitted = '<a href="'.$urlbase.'submissions.php?id='.$this->cm->id.'">'.
dd97c328 398 get_string('noattempts', 'assignment').'</a>';
ba16713f 399 }
ba16713f 400 } else {
4f0c2d00 401 if (isloggedin()) {
ba16713f 402 if ($submission = $this->get_submission($USER->id)) {
403 if ($submission->timemodified) {
1e4343a0 404 if ($submission->timemodified <= $this->assignment->timedue || empty($this->assignment->timedue)) {
ba16713f 405 $submitted = '<span class="early">'.userdate($submission->timemodified).'</span>';
406 } else {
407 $submitted = '<span class="late">'.userdate($submission->timemodified).'</span>';
408 }
409 }
410 }
411 }
412 }
413
414 return $submitted;
415 }
416
417
256578f6 418 /**
419 * @todo Document this function
420 */
436cfa9f 421 function setup_elements(&$mform) {
45fa3412 422
436cfa9f 423 }
424
493a82f6
DC
425 /**
426 * Any preprocessing needed for the settings form for
427 * this assignment type
428 *
429 * @param array $default_values - array to fill in with the default values
430 * in the form 'formelement' => 'value'
431 * @param object $form - the form that is to be displayed
432 * @return none
433 */
434 function form_data_preprocessing(&$default_values, $form) {
435 }
436
437 /**
438 * Any extra validation checks needed for the settings
439 * form for this assignment type
440 *
441 * See lib/formslib.php, 'validation' function for details
442 */
443 function form_validation($data, $files) {
444 return array();
445 }
446
7af1e882 447 /**
448 * Create a new assignment activity
449 *
450 * Given an object containing all the necessary data,
7cac0c4b 451 * (defined by the form in mod_form.php) this function
7af1e882 452 * will create a new instance and return the id number
453 * of the new instance.
454 * The due data is added to the calendar
455 * This is common to all assignment types.
456 *
256578f6 457 * @global object
458 * @global object
459 * @param object $assignment The data from the form on mod_form.php
7af1e882 460 * @return int The id of the assignment
461 */
b0f2597e 462 function add_instance($assignment) {
c18269c7 463 global $COURSE, $DB;
b0f2597e 464
465 $assignment->timemodified = time();
7bddd4b7 466 $assignment->courseid = $assignment->course;
38147229 467
9d97f08e
PS
468 $returnid = $DB->insert_record("assignment", $assignment);
469 $assignment->id = $returnid;
470
471 if ($assignment->timedue) {
39790bd8 472 $event = new stdClass();
9d97f08e
PS
473 $event->name = $assignment->name;
474 $event->description = format_module_intro('assignment', $assignment, $assignment->coursemodule);
475 $event->courseid = $assignment->course;
476 $event->groupid = 0;
477 $event->userid = 0;
478 $event->modulename = 'assignment';
479 $event->instance = $returnid;
480 $event->eventtype = 'due';
481 $event->timestart = $assignment->timedue;
482 $event->timeduration = 0;
483
484 calendar_event::create($event);
736f191c 485 }
486
9d97f08e 487 assignment_grade_item_update($assignment);
7bddd4b7 488
736f191c 489 return $returnid;
b0f2597e 490 }
d699cd1e 491
7af1e882 492 /**
493 * Deletes an assignment activity
494 *
1f8c6549 495 * Deletes all database records, files and calendar events for this assignment.
256578f6 496 *
497 * @global object
498 * @global object
499 * @param object $assignment The assignment to be deleted
7af1e882 500 * @return boolean False indicates error
501 */
b0f2597e 502 function delete_instance($assignment) {
c18269c7 503 global $CFG, $DB;
1f8c6549 504
ada917d5 505 $assignment->courseid = $assignment->course;
506
736f191c 507 $result = true;
508
fa686bc4 509 // now get rid of all files
dc85b32c 510 $fs = get_file_storage();
511 if ($cm = get_coursemodule_from_instance('assignment', $assignment->id)) {
512 $context = get_context_instance(CONTEXT_MODULE, $cm->id);
fa686bc4 513 $fs->delete_area_files($context->id);
dc85b32c 514 }
515
c18269c7 516 if (! $DB->delete_records('assignment_submissions', array('assignment'=>$assignment->id))) {
736f191c 517 $result = false;
518 }
519
77318f47 520 if (! $DB->delete_records('event', array('modulename'=>'assignment', 'instance'=>$assignment->id))) {
736f191c 521 $result = false;
522 }
523
77318f47 524 if (! $DB->delete_records('assignment', array('id'=>$assignment->id))) {
736f191c 525 $result = false;
526 }
cc3b3fae 527 $mod = $DB->get_field('modules','id',array('name'=>'assignment'));
45fa3412 528
45fa3412 529 assignment_grade_item_delete($assignment);
ada917d5 530
736f191c 531 return $result;
b0f2597e 532 }
d699cd1e 533
7af1e882 534 /**
535 * Updates a new assignment activity
536 *
537 * Given an object containing all the necessary data,
7cac0c4b 538 * (defined by the form in mod_form.php) this function
7af1e882 539 * will update the assignment instance and return the id number
540 * The due date is updated in the calendar
541 * This is common to all assignment types.
542 *
256578f6 543 * @global object
544 * @global object
545 * @param object $assignment The data from the form on mod_form.php
7efcb735 546 * @return bool success
7af1e882 547 */
b0f2597e 548 function update_instance($assignment) {
c18269c7 549 global $COURSE, $DB;
b0f2597e 550
38147229 551 $assignment->timemodified = time();
38147229 552
b0f2597e 553 $assignment->id = $assignment->instance;
7bddd4b7 554 $assignment->courseid = $assignment->course;
736f191c 555
9d749339 556 $DB->update_record('assignment', $assignment);
736f191c 557
7bddd4b7 558 if ($assignment->timedue) {
39790bd8 559 $event = new stdClass();
736f191c 560
c18269c7 561 if ($event->id = $DB->get_field('event', 'id', array('modulename'=>'assignment', 'instance'=>$assignment->id))) {
736f191c 562
7bddd4b7 563 $event->name = $assignment->name;
dc5c2bd9 564 $event->description = format_module_intro('assignment', $assignment, $assignment->coursemodule);
7bddd4b7 565 $event->timestart = $assignment->timedue;
736f191c 566
9b72d37e
SH
567 $calendarevent = calendar_event::load($event->id);
568 $calendarevent->update($event);
47263937 569 } else {
39790bd8 570 $event = new stdClass();
7bddd4b7 571 $event->name = $assignment->name;
dc5c2bd9 572 $event->description = format_module_intro('assignment', $assignment, $assignment->coursemodule);
7bddd4b7 573 $event->courseid = $assignment->course;
574 $event->groupid = 0;
575 $event->userid = 0;
576 $event->modulename = 'assignment';
577 $event->instance = $assignment->id;
578 $event->eventtype = 'due';
579 $event->timestart = $assignment->timedue;
580 $event->timeduration = 0;
581
9b72d37e 582 calendar_event::create($event);
736f191c 583 }
7bddd4b7 584 } else {
c18269c7 585 $DB->delete_records('event', array('modulename'=>'assignment', 'instance'=>$assignment->id));
736f191c 586 }
587
7bddd4b7 588 // get existing grade item
45fa3412 589 assignment_grade_item_update($assignment);
7bddd4b7 590
591 return true;
592 }
593
594 /**
45fa3412 595 * Update grade item for this submission.
7bddd4b7 596 */
45fa3412 597 function update_grade($submission) {
612607bd 598 assignment_update_grades($this->assignment, $submission->userid);
b0f2597e 599 }
600
7af1e882 601 /**
b0f2597e 602 * Top-level function for handling of submissions called by submissions.php
7af1e882 603 *
604 * This is for handling the teacher interaction with the grading interface
605 * This should be suitable for most assignment types.
606 *
256578f6 607 * @global object
608 * @param string $mode Specifies the kind of teacher interaction taking place
b0f2597e 609 */
610 function submissions($mode) {
9bf660b3 611 ///The main switch is changed to facilitate
612 ///1) Batch fast grading
613 ///2) Skip to the next one on the popup
614 ///3) Save and Skip to the next one on the popup
45fa3412 615
9bf660b3 616 //make user global so we can use the id
a19dffc0 617 global $USER, $OUTPUT, $DB, $PAGE;
45fa3412 618
de75c481 619 $mailinfo = optional_param('mailinfo', null, PARAM_BOOL);
d2b6ee29 620
261b585d 621 if (optional_param('next', null, PARAM_BOOL)) {
d2b6ee29 622 $mode='next';
623 }
261b585d 624 if (optional_param('saveandnext', null, PARAM_BOOL)) {
d2b6ee29 625 $mode='saveandnext';
626 }
627
2dc5d980 628 if (is_null($mailinfo)) {
fdb797ad
RW
629 if (optional_param('sesskey', null, PARAM_BOOL)) {
630 set_user_preference('assignment_mailinfo', $mailinfo);
631 } else {
632 $mailinfo = get_user_preferences('assignment_mailinfo', 0);
633 }
2dc5d980 634 } else {
635 set_user_preference('assignment_mailinfo', $mailinfo);
de75c481 636 }
d2b6ee29 637
36937f02
MG
638 if (!($this->validate_and_preprocess_feedback())) {
639 // form was submitted ('Save' or 'Save and next' was pressed, but validation failed)
640 $this->display_submission();
641 return;
642 }
643
b0f2597e 644 switch ($mode) {
d2b6ee29 645 case 'grade': // We are in a main window grading
b0f2597e 646 if ($submission = $this->process_feedback()) {
d2b6ee29 647 $this->display_submissions(get_string('changessaved'));
648 } else {
649 $this->display_submissions();
b0f2597e 650 }
b0f2597e 651 break;
9cc9b7c1 652
d2b6ee29 653 case 'single': // We are in a main window displaying one submission
654 if ($submission = $this->process_feedback()) {
655 $this->display_submissions(get_string('changessaved'));
656 } else {
657 $this->display_submission();
658 }
b0f2597e 659 break;
a56d79cd 660
1648afb2 661 case 'all': // Main window, display everything
b0f2597e 662 $this->display_submissions();
663 break;
082215e6 664
9bf660b3 665 case 'fastgrade':
082215e6 666 ///do the fast grading stuff - this process should work for all 3 subclasses
39e11905 667 $grading = false;
16907e53 668 $commenting = false;
39e11905 669 $col = false;
ea6432fe 670 if (isset($_POST['submissioncomment'])) {
671 $col = 'submissioncomment';
16907e53 672 $commenting = true;
673 }
674 if (isset($_POST['menu'])) {
39e11905 675 $col = 'menu';
16907e53 676 $grading = true;
677 }
39e11905 678 if (!$col) {
ea6432fe 679 //both submissioncomment and grade columns collapsed..
45fa3412 680 $this->display_submissions();
16907e53 681 break;
682 }
2dc5d980 683
39e11905 684 foreach ($_POST[$col] as $id => $unusedvalue){
77f4b17b 685
686 $id = (int)$id; //clean parameter name
cc03871b 687
688 $this->process_outcomes($id);
689
39e11905 690 if (!$submission = $this->get_submission($id)) {
691 $submission = $this->prepare_new_submission($id);
692 $newsubmission = true;
693 } else {
694 $newsubmission = false;
695 }
696 unset($submission->data1); // Don't need to update this.
697 unset($submission->data2); // Don't need to update this.
16907e53 698
9bf660b3 699 //for fast grade, we need to check if any changes take place
16907e53 700 $updatedb = false;
701
702 if ($grading) {
703 $grade = $_POST['menu'][$id];
39e11905 704 $updatedb = $updatedb || ($submission->grade != $grade);
705 $submission->grade = $grade;
16907e53 706 } else {
39e11905 707 if (!$newsubmission) {
708 unset($submission->grade); // Don't need to update this.
709 }
16907e53 710 }
711 if ($commenting) {
ea6432fe 712 $commentvalue = trim($_POST['submissioncomment'][$id]);
5053f00f 713 $updatedb = $updatedb || ($submission->submissioncomment != $commentvalue);
ea6432fe 714 $submission->submissioncomment = $commentvalue;
16907e53 715 } else {
ea6432fe 716 unset($submission->submissioncomment); // Don't need to update this.
9bf660b3 717 }
718
39e11905 719 $submission->teacher = $USER->id;
2dc5d980 720 if ($updatedb) {
721 $submission->mailed = (int)(!$mailinfo);
722 }
723
39e11905 724 $submission->timemarked = time();
725
726 //if it is not an update, we don't change the last modified time etc.
ea6432fe 727 //this will also not write into database if no submissioncomment and grade is entered.
39e11905 728
16907e53 729 if ($updatedb){
39e11905 730 if ($newsubmission) {
39f563ed 731 if (!isset($submission->submissioncomment)) {
732 $submission->submissioncomment = '';
733 }
9d749339 734 $sid = $DB->insert_record('assignment_submissions', $submission);
7bddd4b7 735 $submission->id = $sid;
39e11905 736 } else {
9d749339 737 $DB->update_record('assignment_submissions', $submission);
7bddd4b7 738 }
739
91421f3e 740 // trigger grade event
45fa3412 741 $this->update_grade($submission);
7bddd4b7 742
39e11905 743 //add to log only if updating
45fa3412 744 add_to_log($this->course->id, 'assignment', 'update grades',
0f66aced 745 'submissions.php?id='.$this->cm->id.'&user='.$submission->userid,
45fa3412 746 $submission->userid, $this->cm->id);
9bf660b3 747 }
45fa3412 748
749 }
cc03871b 750
3a003ead 751 $message = $OUTPUT->notification(get_string('changessaved'), 'notifysuccess');
fb81abe1 752
753 $this->display_submissions($message);
9bf660b3 754 break;
39e11905 755
756
9bf660b3 757 case 'saveandnext':
758 ///We are in pop up. save the current one and go to the next one.
759 //first we save the current changes
760 if ($submission = $this->process_feedback()) {
761 //print_heading(get_string('changessaved'));
d2b6ee29 762 //$extra_javascript = $this->update_main_listing($submission);
9bf660b3 763 }
45fa3412 764
d2b6ee29 765 case 'next':
766 /// We are currently in pop up, but we want to skip to next one without saving.
767 /// This turns out to be similar to a single case
768 /// The URL used is for the next submission.
769 $offset = required_param('offset', PARAM_INT);
770 $nextid = required_param('nextid', PARAM_INT);
771 $id = required_param('id', PARAM_INT);
89a4471b 772 $filter = optional_param('filter', self::FILTER_ALL, PARAM_INT);
70eddb71
ARN
773
774 if ($mode == 'next' || $filter !== self::FILTER_REQUIRE_GRADING) {
775 $offset = (int)$offset+1;
776 }
89a4471b
ARN
777 $redirect = new moodle_url('submissions.php',
778 array('id' => $id, 'offset' => $offset, 'userid' => $nextid,
779 'mode' => 'single', 'filter' => $filter));
780
781 redirect($redirect);
9bf660b3 782 break;
45fa3412 783
2d274675
AB
784 case 'singlenosave':
785 $this->display_submission();
786 break;
787
9bf660b3 788 default:
789 echo "something seriously is wrong!!";
45fa3412 790 break;
a56d79cd 791 }
b0f2597e 792 }
45fa3412 793
9e2eca0f
MG
794 /**
795 * Checks if grading method allows quickgrade mode. At the moment it is hardcoded
796 * that advanced grading methods do not allow quickgrade.
797 *
798 * Assignment type plugins are not allowed to override this method
799 *
800 * @return boolean
801 */
802 public final function quickgrade_mode_allowed() {
803 global $CFG;
804 require_once("$CFG->dirroot/grade/grading/lib.php");
805 if ($controller = get_grading_manager($this->context, 'mod_assignment', 'submission')->get_active_controller()) {
806 return false;
807 }
808 return true;
809 }
810
7af1e882 811 /**
256578f6 812 * Helper method updating the listing on the main script from popup using javascript
813 *
814 * @global object
815 * @global object
816 * @param $submission object The submission whose data is to be updated on the main page
817 */
be86672d 818 function update_main_listing($submission) {
a9573c08 819 global $SESSION, $CFG, $OUTPUT;
45fa3412 820
73963212 821 $output = '';
822
9bf660b3 823 $perpage = get_user_preferences('assignment_perpage', 10);
be86672d 824
9e2eca0f 825 $quickgrade = get_user_preferences('assignment_quickgrade', 0) && $this->quickgrade_mode_allowed();
45fa3412 826
be86672d 827 /// Run some Javascript to try and update the parent page
73963212 828 $output .= '<script type="text/javascript">'."\n<!--\n";
ea6432fe 829 if (empty($SESSION->flextable['mod-assignment-submissions']->collapse['submissioncomment'])) {
9bf660b3 830 if ($quickgrade){
16fc2088 831 $output.= 'opener.document.getElementById("submissioncomment'.$submission->userid.'").value="'
ea6432fe 832 .trim($submission->submissioncomment).'";'."\n";
9bf660b3 833 } else {
73963212 834 $output.= 'opener.document.getElementById("com'.$submission->userid.
ea6432fe 835 '").innerHTML="'.shorten_text(trim(strip_tags($submission->submissioncomment)), 15)."\";\n";
9bf660b3 836 }
be86672d 837 }
9bf660b3 838
839 if (empty($SESSION->flextable['mod-assignment-submissions']->collapse['grade'])) {
840 //echo optional_param('menuindex');
841 if ($quickgrade){
16fc2088 842 $output.= 'opener.document.getElementById("menumenu'.$submission->userid.
843 '").selectedIndex="'.optional_param('menuindex', 0, PARAM_INT).'";'."\n";
9bf660b3 844 } else {
73963212 845 $output.= 'opener.document.getElementById("g'.$submission->userid.'").innerHTML="'.
9bf660b3 846 $this->display_grade($submission->grade)."\";\n";
45fa3412 847 }
848 }
9bf660b3 849 //need to add student's assignments in there too.
73097f07 850 if (empty($SESSION->flextable['mod-assignment-submissions']->collapse['timemodified']) &&
851 $submission->timemodified) {
73963212 852 $output.= 'opener.document.getElementById("ts'.$submission->userid.
3a935caf 853 '").innerHTML="'.addslashes_js($this->print_student_answer($submission->userid)).userdate($submission->timemodified)."\";\n";
be86672d 854 }
45fa3412 855
73097f07 856 if (empty($SESSION->flextable['mod-assignment-submissions']->collapse['timemarked']) &&
857 $submission->timemarked) {
73963212 858 $output.= 'opener.document.getElementById("tt'.$submission->userid.
be86672d 859 '").innerHTML="'.userdate($submission->timemarked)."\";\n";
860 }
45fa3412 861
be86672d 862 if (empty($SESSION->flextable['mod-assignment-submissions']->collapse['status'])) {
73963212 863 $output.= 'opener.document.getElementById("up'.$submission->userid.'").className="s1";';
9bf660b3 864 $buttontext = get_string('update');
a9573c08 865 $url = new moodle_url('/mod/assignment/submissions.php', array(
866 'id' => $this->cm->id,
867 'userid' => $submission->userid,
e7521559 868 'mode' => 'single',
a9573c08 869 'offset' => (optional_param('offset', '', PARAM_INT)-1)));
57cd3739 870 $button = $OUTPUT->action_link($url, $buttontext, new popup_action('click', $url, 'grade'.$submission->userid, array('height' => 450, 'width' => 700)), array('ttile'=>$buttontext));
e7521559 871
57cd3739 872 $output .= 'opener.document.getElementById("up'.$submission->userid.'").innerHTML="'.addslashes_js($button).'";';
45fa3412 873 }
f1af7aaa 874
5978010d 875 $grading_info = grade_get_grades($this->course->id, 'mod', 'assignment', $this->assignment->id, $submission->userid);
876
877 if (empty($SESSION->flextable['mod-assignment-submissions']->collapse['finalgrade'])) {
878 $output.= 'opener.document.getElementById("finalgrade_'.$submission->userid.
879 '").innerHTML="'.$grading_info->items[0]->grades[$submission->userid]->str_grade.'";'."\n";
880 }
881
882 if (!empty($CFG->enableoutcomes) and empty($SESSION->flextable['mod-assignment-submissions']->collapse['outcome'])) {
fcac8e51 883
884 if (!empty($grading_info->outcomes)) {
d886a7ea 885 foreach($grading_info->outcomes as $n=>$outcome) {
886 if ($outcome->grades[$submission->userid]->locked) {
887 continue;
888 }
cc03871b 889
d886a7ea 890 if ($quickgrade){
891 $output.= 'opener.document.getElementById("outcome_'.$n.'_'.$submission->userid.
892 '").selectedIndex="'.$outcome->grades[$submission->userid]->grade.'";'."\n";
893
894 } else {
895 $options = make_grades_menu(-$outcome->scaleid);
896 $options[0] = get_string('nooutcome', 'grades');
897 $output.= 'opener.document.getElementById("outcome_'.$n.'_'.$submission->userid.'").innerHTML="'.$options[$outcome->grades[$submission->userid]->grade]."\";\n";
898 }
cc03871b 899
900 }
901 }
902 }
903
73963212 904 $output .= "\n-->\n</script>";
905 return $output;
be86672d 906 }
d699cd1e 907
7af1e882 908 /**
909 * Return a grade in user-friendly form, whether it's a scale or not
45fa3412 910 *
256578f6 911 * @global object
912 * @param mixed $grade
7af1e882 913 * @return string User-friendly representation of grade
d59269cf 914 */
915 function display_grade($grade) {
74d7d735 916 global $DB;
d59269cf 917
c86aa2a4 918 static $scalegrades = array(); // Cache scales for each assignment - they might have different scales!!
d59269cf 919
920 if ($this->assignment->grade >= 0) { // Normal number
082215e6 921 if ($grade == -1) {
922 return '-';
923 } else {
924 return $grade.' / '.$this->assignment->grade;
925 }
d59269cf 926
927 } else { // Scale
c86aa2a4 928 if (empty($scalegrades[$this->assignment->id])) {
74d7d735 929 if ($scale = $DB->get_record('scale', array('id'=>-($this->assignment->grade)))) {
c86aa2a4 930 $scalegrades[$this->assignment->id] = make_menu_from_list($scale->scale);
d59269cf 931 } else {
932 return '-';
933 }
934 }
c86aa2a4 935 if (isset($scalegrades[$this->assignment->id][$grade])) {
936 return $scalegrades[$this->assignment->id][$grade];
0f7d4e5e 937 }
39e11905 938 return '-';
d59269cf 939 }
940 }
941
7af1e882 942 /**
b0f2597e 943 * Display a single submission, ready for grading on a popup window
7af1e882 944 *
ea6432fe 945 * This default method prints the teacher info and submissioncomment box at the top and
7af1e882 946 * the student info and submission at the bottom.
947 * This method also fetches the necessary data in order to be able to
948 * provide a "Next submission" button.
949 * Calls preprocess_submission() to give assignment type plug-ins a chance
950 * to process submissions before they are graded
951 * This method gets its arguments from the page parameters userid and offset
256578f6 952 *
953 * @global object
954 * @global object
955 * @param string $extra_javascript
b0f2597e 956 */
291ee134 957 function display_submission($offset=-1,$userid =-1, $display=true) {
36937f02 958 global $CFG, $DB, $PAGE, $OUTPUT, $USER;
cc03871b 959 require_once($CFG->libdir.'/gradelib.php');
dd97c328 960 require_once($CFG->libdir.'/tablelib.php');
291ee134 961 require_once("$CFG->dirroot/repository/lib.php");
fba356f3 962 require_once("$CFG->dirroot/grade/grading/lib.php");
261b585d 963 if ($userid==-1) {
964 $userid = required_param('userid', PARAM_INT);
965 }
966 if ($offset==-1) {
967 $offset = required_param('offset', PARAM_INT);//offset for where to start looking for student.
968 }
fdb797ad 969 $filter = optional_param('filter', 0, PARAM_INT);
d699cd1e 970
5053f00f 971 if (!$user = $DB->get_record('user', array('id'=>$userid))) {
a939f681 972 print_error('nousers');
b0f2597e 973 }
d699cd1e 974
39e11905 975 if (!$submission = $this->get_submission($user->id)) {
976 $submission = $this->prepare_new_submission($userid);
b0f2597e 977 }
b0f2597e 978 if ($submission->timemodified > $submission->timemarked) {
979 $subtype = 'assignmentnew';
980 } else {
981 $subtype = 'assignmentold';
982 }
d699cd1e 983
5978010d 984 $grading_info = grade_get_grades($this->course->id, 'mod', 'assignment', $this->assignment->id, array($user->id));
d2b6ee29 985 $gradingdisabled = $grading_info->items[0]->grades[$userid]->locked || $grading_info->items[0]->grades[$userid]->overridden;
5978010d 986
0cfafdc7 987 /// construct SQL, using current offset to find the data of the next student
9bf660b3 988 $course = $this->course;
989 $assignment = $this->assignment;
990 $cm = $this->cm;
16fc2088 991 $context = get_context_instance(CONTEXT_MODULE, $cm->id);
d699cd1e 992
54c37fbd
RW
993 //reset filter to all for offline assignment
994 if ($assignment->assignmenttype == 'offline' && $filter == self::FILTER_SUBMITTED) {
995 $filter = self::FILTER_ALL;
996 }
7bddd4b7 997 /// Get all ppl that can submit assignments
0cfafdc7 998
ba3dc7b4 999 $currentgroup = groups_get_activity_group($cm);
4ac9f470 1000 $users = get_enrolled_users($context, 'mod/assignment:submit', $currentgroup, 'u.id');
c7bb34b6 1001 if ($users) {
dd97c328 1002 $users = array_keys($users);
c7bb34b6
SH
1003 // if groupmembersonly used, remove users who are not in any group
1004 if (!empty($CFG->enablegroupmembersonly) and $cm->groupmembersonly) {
1005 if ($groupingusers = groups_get_grouping_members($cm->groupingid, 'u.id', 'u.id')) {
1006 $users = array_intersect($users, array_keys($groupingusers));
1007 }
dd97c328 1008 }
02828119 1009 }
1010
082215e6 1011 $nextid = 0;
fdb797ad 1012 $where = '';
54c37fbd 1013 if($filter == self::FILTER_SUBMITTED) {
fdb797ad 1014 $where .= 's.timemodified > 0 AND ';
54c37fbd 1015 } else if($filter == self::FILTER_REQUIRE_GRADING) {
fdb797ad
RW
1016 $where .= 's.timemarked < s.timemodified AND ';
1017 }
dd97c328 1018
1019 if ($users) {
3a11c09f
PS
1020 $userfields = user_picture::fields('u', array('lastaccess'));
1021 $select = "SELECT $userfields,
dd97c328 1022 s.id AS submissionid, s.grade, s.submissioncomment,
8c93ab4e
SB
1023 s.timemodified, s.timemarked,
1024 CASE WHEN s.timemarked > 0 AND s.timemarked >= s.timemodified THEN 1
1025 ELSE 0 END AS status ";
1026
5053f00f 1027 $sql = 'FROM {user} u '.
1028 'LEFT JOIN {assignment_submissions} s ON u.id = s.userid
fdb797ad
RW
1029 AND s.assignment = '.$this->assignment->id.' '.
1030 'WHERE '.$where.'u.id IN ('.implode(',', $users).') ';
dd97c328 1031
9baf2670 1032 if ($sort = flexible_table::get_sort_for_table('mod-assignment-submissions')) {
dd97c328 1033 $sort = 'ORDER BY '.$sort.' ';
1034 }
d2b6ee29 1035 $auser = $DB->get_records_sql($select.$sql.$sort, null, $offset, 2);
dd97c328 1036
d2b6ee29 1037 if (is_array($auser) && count($auser)>1) {
1038 $nextuser = next($auser);
dd97c328 1039 $nextid = $nextuser->id;
1040 }
9bf660b3 1041 }
d699cd1e 1042
b0f2597e 1043 if ($submission->teacher) {
5053f00f 1044 $teacher = $DB->get_record('user', array('id'=>$submission->teacher));
b0f2597e 1045 } else {
1046 global $USER;
1047 $teacher = $USER;
1048 }
de75c481 1049
01e2fdfe 1050 $this->preprocess_submission($submission);
1051
6bdfef5d 1052 $mformdata = new stdClass();
d2b6ee29 1053 $mformdata->context = $this->context;
1054 $mformdata->maxbytes = $this->course->maxbytes;
1055 $mformdata->courseid = $this->course->id;
1056 $mformdata->teacher = $teacher;
1057 $mformdata->assignment = $assignment;
1058 $mformdata->submission = $submission;
1059 $mformdata->lateness = $this->display_lateness($submission->timemodified);
1060 $mformdata->auser = $auser;
1061 $mformdata->user = $user;
1062 $mformdata->offset = $offset;
1063 $mformdata->userid = $userid;
1064 $mformdata->cm = $this->cm;
1065 $mformdata->grading_info = $grading_info;
1066 $mformdata->enableoutcomes = $CFG->enableoutcomes;
1067 $mformdata->grade = $this->assignment->grade;
1068 $mformdata->gradingdisabled = $gradingdisabled;
d2b6ee29 1069 $mformdata->nextid = $nextid;
1070 $mformdata->submissioncomment= $submission->submissioncomment;
1071 $mformdata->submissioncommentformat= FORMAT_HTML;
2a576f94 1072 $mformdata->submission_content= $this->print_user_files($user->id,true);
fdb797ad 1073 $mformdata->filter = $filter;
be34802d 1074 $mformdata->mailinfo = get_user_preferences('assignment_mailinfo', 0);
291ee134
AB
1075 if ($assignment->assignmenttype == 'upload') {
1076 $mformdata->fileui_options = array('subdirs'=>1, 'maxbytes'=>$assignment->maxbytes, 'maxfiles'=>$assignment->var1, 'accepted_types'=>'*', 'return_types'=>FILE_INTERNAL);
1077 } elseif ($assignment->assignmenttype == 'uploadsingle') {
1078 $mformdata->fileui_options = array('subdirs'=>0, 'maxbytes'=>$CFG->userquota, 'maxfiles'=>1, 'accepted_types'=>'*', 'return_types'=>FILE_INTERNAL);
1079 }
0e2a1d75
MG
1080 $advancedgradingwarning = false;
1081 $gradingmanager = get_grading_manager($this->context, 'mod_assignment', 'submission');
1082 if ($gradingmethod = $gradingmanager->get_active_method()) {
1083 $controller = $gradingmanager->get_controller($gradingmethod);
1084 if ($controller->is_form_available()) {
1085 $itemid = null;
1086 if (!empty($submission->id)) {
1087 $itemid = $submission->id;
1088 }
71380f2f
MG
1089 if ($gradingdisabled && $itemid) {
1090 $mformdata->advancedgradinginstance = $controller->get_current_instance($USER->id, $itemid);
1091 } else if (!$gradingdisabled) {
1092 $instanceid = optional_param('advancedgradinginstanceid', 0, PARAM_INT);
1093 $mformdata->advancedgradinginstance = $controller->get_or_create_instance($instanceid, $USER->id, $itemid);
1094 }
0e2a1d75
MG
1095 } else {
1096 $advancedgradingwarning = $controller->form_unavailable_notification();
18e6298c 1097 }
fba356f3 1098 }
de75c481 1099
cd0fe5a4 1100 $submitform = new mod_assignment_grading_form( null, $mformdata );
d2b6ee29 1101
291ee134
AB
1102 if (!$display) {
1103 $ret_data = new stdClass();
1104 $ret_data->mform = $submitform;
18e6298c
MG
1105 if (isset($mformdata->fileui_options)) {
1106 $ret_data->fileui_options = $mformdata->fileui_options;
1107 }
291ee134
AB
1108 return $ret_data;
1109 }
1110
261b585d 1111 if ($submitform->is_cancelled()) {
d2b6ee29 1112 redirect('submissions.php?id='.$this->cm->id);
1113 }
1114
1115 $submitform->set_data($mformdata);
1116
1117 $PAGE->set_title($this->course->fullname . ': ' .get_string('feedback', 'assignment').' - '.fullname($user, true));
1118 $PAGE->set_heading($this->course->fullname);
291ee134
AB
1119 $PAGE->navbar->add(get_string('submissions', 'assignment'), new moodle_url('/mod/assignment/submissions.php', array('id'=>$cm->id)));
1120 $PAGE->navbar->add(fullname($user, true));
b0f2597e 1121
d2b6ee29 1122 echo $OUTPUT->header();
1123 echo $OUTPUT->heading(get_string('feedback', 'assignment').': '.fullname($user, true));
2dc5d980 1124
d2b6ee29 1125 // display mform here...
0e2a1d75
MG
1126 if ($advancedgradingwarning) {
1127 echo $OUTPUT->notification($advancedgradingwarning, 'error');
1128 }
d2b6ee29 1129 $submitform->display();
55b4d096 1130
1131 $customfeedback = $this->custom_feedbackform($submission, true);
1132 if (!empty($customfeedback)) {
45fa3412 1133 echo $customfeedback;
55b4d096 1134 }
1135
256d2850 1136 echo $OUTPUT->footer();
d699cd1e 1137 }
1138
7af1e882 1139 /**
01e2fdfe 1140 * Preprocess submission before grading
7af1e882 1141 *
1142 * Called by display_submission()
1143 * The default type does nothing here.
256578f6 1144 *
1145 * @param object $submission The submission object
01e2fdfe 1146 */
1147 function preprocess_submission(&$submission) {
1148 }
d699cd1e 1149
7af1e882 1150 /**
b0f2597e 1151 * Display all the submissions ready for grading
256578f6 1152 *
1153 * @global object
1154 * @global object
1155 * @global object
1156 * @global object
1157 * @param string $message
1158 * @return bool|void
b0f2597e 1159 */
fb81abe1 1160 function display_submissions($message='') {
b98b15d7 1161 global $CFG, $DB, $USER, $DB, $OUTPUT, $PAGE;
cc03871b 1162 require_once($CFG->libdir.'/gradelib.php');
3446205d 1163
9bf660b3 1164 /* first we check to see if the form has just been submitted
1165 * to request user_preference updates
1166 */
de75c481 1167
fdb797ad 1168 $filters = array(self::FILTER_ALL => get_string('all'),
fdb797ad
RW
1169 self::FILTER_REQUIRE_GRADING => get_string('requiregrading', 'assignment'));
1170
54c37fbd
RW
1171 $updatepref = optional_param('updatepref', 0, PARAM_BOOL);
1172 if ($updatepref) {
16907e53 1173 $perpage = optional_param('perpage', 10, PARAM_INT);
9bf660b3 1174 $perpage = ($perpage <= 0) ? 10 : $perpage ;
fdb797ad 1175 $filter = optional_param('filter', 0, PARAM_INT);
9bf660b3 1176 set_user_preference('assignment_perpage', $perpage);
de75c481 1177 set_user_preference('assignment_quickgrade', optional_param('quickgrade', 0, PARAM_BOOL));
fdb797ad 1178 set_user_preference('assignment_filter', $filter);
9bf660b3 1179 }
1b5910c4 1180
45fa3412 1181 /* next we get perpage and quickgrade (allow quick grade) params
9bf660b3 1182 * from database
1183 */
1184 $perpage = get_user_preferences('assignment_perpage', 10);
9e2eca0f 1185 $quickgrade = get_user_preferences('assignment_quickgrade', 0) && $this->quickgrade_mode_allowed();
fdb797ad 1186 $filter = get_user_preferences('assignment_filter', 0);
fcac8e51 1187 $grading_info = grade_get_grades($this->course->id, 'mod', 'assignment', $this->assignment->id);
45fa3412 1188
fcac8e51 1189 if (!empty($CFG->enableoutcomes) and !empty($grading_info->outcomes)) {
e46f4d11 1190 $uses_outcomes = true;
1191 } else {
1192 $uses_outcomes = false;
1193 }
1194
16907e53 1195 $page = optional_param('page', 0, PARAM_INT);
b0f2597e 1196 $strsaveallfeedback = get_string('saveallfeedback', 'assignment');
d0ac6bc2 1197
b0f2597e 1198 /// Some shortcuts to make the code read better
45fa3412 1199
b0f2597e 1200 $course = $this->course;
1201 $assignment = $this->assignment;
1202 $cm = $this->cm;
e512715b 1203 $hassubmission = false;
45fa3412 1204
54c37fbd
RW
1205 // reset filter to all for offline assignment only.
1206 if ($assignment->assignmenttype == 'offline') {
1207 if ($filter == self::FILTER_SUBMITTED) {
1208 $filter = self::FILTER_ALL;
1209 }
1210 } else {
1211 $filters[self::FILTER_SUBMITTED] = get_string('submitted', 'assignment');
1212 }
1213
dad55fc5 1214 $tabindex = 1; //tabindex for quick grading tabbing; Not working for dropdowns yet
1215 add_to_log($course->id, 'assignment', 'view submission', 'submissions.php?id='.$this->cm->id, $this->assignment->id, $this->cm->id);
96f4a64b 1216
dad55fc5 1217 $PAGE->set_title(format_string($this->assignment->name,true));
d2b6ee29 1218 $PAGE->set_heading($this->course->fullname);
dad55fc5 1219 echo $OUTPUT->header();
1220
fdb797ad 1221 echo '<div class="usersubmissions">';
de75c481 1222
44729427
DM
1223 //hook to allow plagiarism plugins to update status/print links.
1224 plagiarism_update_status($this->course, $this->cm);
1225
fb739b77 1226 $course_context = get_context_instance(CONTEXT_COURSE, $course->id);
1227 if (has_capability('gradereport/grader:view', $course_context) && has_capability('moodle/grade:viewall', $course_context)) {
12dce253 1228 echo '<div class="allcoursegrades"><a href="' . $CFG->wwwroot . '/grade/report/grader/index.php?id=' . $course->id . '">'
b64792f6 1229 . get_string('seeallcoursegrades', 'grades') . '</a></div>';
fb739b77 1230 }
7bddd4b7 1231
fb81abe1 1232 if (!empty($message)) {
1233 echo $message; // display messages here if any
1234 }
1235
2d7617c6 1236 $context = get_context_instance(CONTEXT_MODULE, $cm->id);
7bddd4b7 1237
dd97c328 1238 /// Check to see if groups are being used in this assignment
1239
7bddd4b7 1240 /// find out current groups mode
ba3dc7b4 1241 $groupmode = groups_get_activity_groupmode($cm);
1242 $currentgroup = groups_get_activity_group($cm, true);
f1035deb 1243 groups_print_activity_menu($cm, $CFG->wwwroot . '/mod/assignment/submissions.php?id=' . $this->cm->id);
7bddd4b7 1244
13b3f4d4
MG
1245 /// Print quickgrade form around the table
1246 if ($quickgrade) {
1247 $formattrs = array();
1248 $formattrs['action'] = new moodle_url('/mod/assignment/submissions.php');
1249 $formattrs['id'] = 'fastg';
1250 $formattrs['method'] = 'post';
1251
1252 echo html_writer::start_tag('form', $formattrs);
1253 echo html_writer::empty_tag('input', array('type'=>'hidden', 'name'=>'id', 'value'=> $this->cm->id));
1254 echo html_writer::empty_tag('input', array('type'=>'hidden', 'name'=>'mode', 'value'=> 'fastgrade'));
1255 echo html_writer::empty_tag('input', array('type'=>'hidden', 'name'=>'page', 'value'=> $page));
1256 echo html_writer::empty_tag('input', array('type'=>'hidden', 'name'=>'sesskey', 'value'=> sesskey()));
1257 }
1258
7bddd4b7 1259 /// Get all ppl that are allowed to submit assignments
7d8b217b 1260 list($esql, $params) = get_enrolled_sql($context, 'mod/assignment:submit', $currentgroup);
de75c481 1261
fdb797ad
RW
1262 if ($filter == self::FILTER_ALL) {
1263 $sql = "SELECT u.id FROM {user} u ".
1264 "LEFT JOIN ($esql) eu ON eu.id=u.id ".
1265 "WHERE u.deleted = 0 AND eu.id=u.id ";
1266 } else {
54c37fbd
RW
1267 $wherefilter = ' AND s.assignment = '. $this->assignment->id;
1268 $assignmentsubmission = "LEFT JOIN {assignment_submissions} s ON (u.id = s.userid) ";
fdb797ad 1269 if($filter == self::FILTER_SUBMITTED) {
54c37fbd
RW
1270 $wherefilter .= ' AND s.timemodified > 0 ';
1271 } else if($filter == self::FILTER_REQUIRE_GRADING && $assignment->assignmenttype != 'offline') {
1272 $wherefilter .= ' AND s.timemarked < s.timemodified ';
1273 } else { // require grading for offline assignment
1274 $assignmentsubmission = "";
1275 $wherefilter = "";
fdb797ad
RW
1276 }
1277
1278 $sql = "SELECT u.id FROM {user} u ".
1279 "LEFT JOIN ($esql) eu ON eu.id=u.id ".
54c37fbd 1280 $assignmentsubmission.
fdb797ad 1281 "WHERE u.deleted = 0 AND eu.id=u.id ".
54c37fbd 1282 $wherefilter;
fdb797ad
RW
1283 }
1284
1285 $users = $DB->get_records_sql($sql, $params);
1286 if (!empty($users)) {
54c37fbd
RW
1287 if($assignment->assignmenttype == 'offline' && $filter == self::FILTER_REQUIRE_GRADING) {
1288 //remove users who has submitted their assignment
1289 foreach ($this->get_submissions() as $submission) {
1290 if (array_key_exists($submission->userid, $users)) {
1291 unset($users[$submission->userid]);
1292 }
1293 }
1294 }
33150205 1295 $users = array_keys($users);
1296 }
ba3dc7b4 1297
dd97c328 1298 // if groupmembersonly used, remove users who are not in any group
98da6021 1299 if ($users and !empty($CFG->enablegroupmembersonly) and $cm->groupmembersonly) {
dd97c328 1300 if ($groupingusers = groups_get_grouping_members($cm->groupingid, 'u.id', 'u.id')) {
1301 $users = array_intersect($users, array_keys($groupingusers));
1302 }
ba3dc7b4 1303 }
91719320 1304
02dd3b9f 1305 $extrafields = get_extra_user_fields($context);
1306 $tablecolumns = array_merge(array('picture', 'fullname'), $extrafields,
1307 array('grade', 'submissioncomment', 'timemodified', 'timemarked', 'status', 'finalgrade'));
e46f4d11 1308 if ($uses_outcomes) {
5978010d 1309 $tablecolumns[] = 'outcome'; // no sorting based on outcomes column
fbaa56b2 1310 }
1311
02dd3b9f 1312 $extrafieldnames = array();
1313 foreach ($extrafields as $field) {
1314 $extrafieldnames[] = get_user_field_name($field);
1315 }
1316 $tableheaders = array_merge(
1317 array('', get_string('fullnameuser')),
1318 $extrafieldnames,
1319 array(
1320 get_string('grade'),
1321 get_string('comment', 'assignment'),
1322 get_string('lastmodified').' ('.get_string('submission', 'assignment').')',
1323 get_string('lastmodified').' ('.get_string('grade').')',
1324 get_string('status'),
1325 get_string('finalgrade', 'grades'),
1326 ));
e46f4d11 1327 if ($uses_outcomes) {
5978010d 1328 $tableheaders[] = get_string('outcome', 'grades');
fbaa56b2 1329 }
91719320 1330
b0f2597e 1331 require_once($CFG->libdir.'/tablelib.php');
1332 $table = new flexible_table('mod-assignment-submissions');
45fa3412 1333
b0f2597e 1334 $table->define_columns($tablecolumns);
1335 $table->define_headers($tableheaders);
fa22fd5f 1336 $table->define_baseurl($CFG->wwwroot.'/mod/assignment/submissions.php?id='.$this->cm->id.'&amp;currentgroup='.$currentgroup);
45fa3412 1337
246444b9 1338 $table->sortable(true, 'lastname');//sorted by lastname by default
b0f2597e 1339 $table->collapsible(true);
1340 $table->initialbars(true);
45fa3412 1341
b0f2597e 1342 $table->column_suppress('picture');
1343 $table->column_suppress('fullname');
45fa3412 1344
b0f2597e 1345 $table->column_class('picture', 'picture');
9437c854 1346 $table->column_class('fullname', 'fullname');
02dd3b9f 1347 foreach ($extrafields as $field) {
1348 $table->column_class($field, $field);
1349 }
9437c854 1350 $table->column_class('grade', 'grade');
ea6432fe 1351 $table->column_class('submissioncomment', 'comment');
9437c854 1352 $table->column_class('timemodified', 'timemodified');
1353 $table->column_class('timemarked', 'timemarked');
1354 $table->column_class('status', 'status');
5978010d 1355 $table->column_class('finalgrade', 'finalgrade');
e46f4d11 1356 if ($uses_outcomes) {
5978010d 1357 $table->column_class('outcome', 'outcome');
fbaa56b2 1358 }
45fa3412 1359
b0f2597e 1360 $table->set_attribute('cellspacing', '0');
1361 $table->set_attribute('id', 'attempts');
9437c854 1362 $table->set_attribute('class', 'submissions');
f30036d3 1363 $table->set_attribute('width', '100%');
45fa3412 1364
5978010d 1365 $table->no_sorting('finalgrade');
1366 $table->no_sorting('outcome');
1367
b0f2597e 1368 // Start working -- this is necessary as soon as the niceties are over
1369 $table->setup();
1370
54c37fbd 1371 /// Construct the SQL
0f21a964
PS
1372 list($where, $params) = $table->get_sql_where();
1373 if ($where) {
b0f2597e 1374 $where .= ' AND ';
1375 }
de75c481 1376
0f21a964 1377 if ($filter == self::FILTER_SUBMITTED) {
de75c481 1378 $where .= 's.timemodified > 0 AND ';
fdb797ad 1379 } else if($filter == self::FILTER_REQUIRE_GRADING) {
54c37fbd
RW
1380 $where = '';
1381 if ($assignment->assignmenttype != 'offline') {
1382 $where .= 's.timemarked < s.timemodified AND ';
1383 }
fdb797ad 1384 }
0f1a97c2 1385
b0f2597e 1386 if ($sort = $table->get_sql_sort()) {
86f65395 1387 $sort = ' ORDER BY '.$sort;
b0f2597e 1388 }
9fa49e22 1389
02dd3b9f 1390 $ufields = user_picture::fields('u', $extrafields);
e512715b
RW
1391 if (!empty($users)) {
1392 $select = "SELECT $ufields,
1393 s.id AS submissionid, s.grade, s.submissioncomment,
8c93ab4e
SB
1394 s.timemodified, s.timemarked,
1395 CASE WHEN s.timemarked > 0 AND s.timemarked >= s.timemodified THEN 1
1396 ELSE 0 END AS status ";
1397
e512715b
RW
1398 $sql = 'FROM {user} u '.
1399 'LEFT JOIN {assignment_submissions} s ON u.id = s.userid
1400 AND s.assignment = '.$this->assignment->id.' '.
1401 'WHERE '.$where.'u.id IN ('.implode(',',$users).') ';
1402
1403 $ausers = $DB->get_records_sql($select.$sql.$sort, $params, $table->get_page_start(), $table->get_page_size());
1404
1405 $table->pagesize($perpage, count($users));
1406
1407 ///offset used to calculate index of student in that particular query, needed for the pop up to know who's next
1408 $offset = $page * $perpage;
1409 $strupdate = get_string('update');
1410 $strgrade = get_string('grade');
1411 $grademenu = make_grades_menu($this->assignment->grade);
1412
1413 if ($ausers !== false) {
1414 $grading_info = grade_get_grades($this->course->id, 'mod', 'assignment', $this->assignment->id, array_keys($ausers));
1415 $endposition = $offset + $perpage;
1416 $currentposition = 0;
1417 foreach ($ausers as $auser) {
1418 if ($currentposition == $offset && $offset < $endposition) {
1419 $final_grade = $grading_info->items[0]->grades[$auser->id];
1420 $grademax = $grading_info->items[0]->grademax;
1421 $final_grade->formatted_grade = round($final_grade->grade,2) .' / ' . round($grademax,2);
1422 $locked_overridden = 'locked';
1423 if ($final_grade->overridden) {
1424 $locked_overridden = 'overridden';
1425 }
fdb797ad 1426
9e2eca0f 1427 // TODO add here code if advanced grading grade must be reviewed => $auser->status=0
1ae9aa2b 1428
e512715b 1429 $picture = $OUTPUT->user_picture($auser);
45fa3412 1430
e512715b
RW
1431 if (empty($auser->submissionid)) {
1432 $auser->grade = -1; //no submission yet
1433 }
45fa3412 1434
e512715b
RW
1435 if (!empty($auser->submissionid)) {
1436 $hassubmission = true;
1437 ///Prints student answer and student modified date
1438 ///attach file or print link to student answer, depending on the type of the assignment.
1439 ///Refer to print_student_answer in inherited classes.
1440 if ($auser->timemodified > 0) {
1441 $studentmodified = '<div id="ts'.$auser->id.'">'.$this->print_student_answer($auser->id)
1442 . userdate($auser->timemodified).'</div>';
1443 } else {
1444 $studentmodified = '<div id="ts'.$auser->id.'">&nbsp;</div>';
1445 }
1446 ///Print grade, dropdown or text
1447 if ($auser->timemarked > 0) {
1448 $teachermodified = '<div id="tt'.$auser->id.'">'.userdate($auser->timemarked).'</div>';
1449
1450 if ($final_grade->locked or $final_grade->overridden) {
1451 $grade = '<div id="g'.$auser->id.'" class="'. $locked_overridden .'">'.$final_grade->formatted_grade.'</div>';
1452 } else if ($quickgrade) {
1453 $attributes = array();
1454 $attributes['tabindex'] = $tabindex++;
1455 $menu = html_writer::select(make_grades_menu($this->assignment->grade), 'menu['.$auser->id.']', $auser->grade, array(-1=>get_string('nograde')), $attributes);
1456 $grade = '<div id="g'.$auser->id.'">'. $menu .'</div>';
1457 } else {
1458 $grade = '<div id="g'.$auser->id.'">'.$this->display_grade($auser->grade).'</div>';
1459 }
45fa3412 1460
e512715b
RW
1461 } else {
1462 $teachermodified = '<div id="tt'.$auser->id.'">&nbsp;</div>';
1463 if ($final_grade->locked or $final_grade->overridden) {
1464 $grade = '<div id="g'.$auser->id.'" class="'. $locked_overridden .'">'.$final_grade->formatted_grade.'</div>';
1465 } else if ($quickgrade) {
1466 $attributes = array();
1467 $attributes['tabindex'] = $tabindex++;
1468 $menu = html_writer::select(make_grades_menu($this->assignment->grade), 'menu['.$auser->id.']', $auser->grade, array(-1=>get_string('nograde')), $attributes);
1469 $grade = '<div id="g'.$auser->id.'">'.$menu.'</div>';
1470 } else {
1471 $grade = '<div id="g'.$auser->id.'">'.$this->display_grade($auser->grade).'</div>';
1472 }
1473 }
1474 ///Print Comment
1475 if ($final_grade->locked or $final_grade->overridden) {
1476 $comment = '<div id="com'.$auser->id.'">'.shorten_text(strip_tags($final_grade->str_feedback),15).'</div>';
1477
1478 } else if ($quickgrade) {
1479 $comment = '<div id="com'.$auser->id.'">'
1480 . '<textarea tabindex="'.$tabindex++.'" name="submissioncomment['.$auser->id.']" id="submissioncomment'
1481 . $auser->id.'" rows="2" cols="20">'.($auser->submissioncomment).'</textarea></div>';
1482 } else {
1483 $comment = '<div id="com'.$auser->id.'">'.shorten_text(strip_tags($auser->submissioncomment),15).'</div>';
1484 }
fdb797ad
RW
1485 } else {
1486 $studentmodified = '<div id="ts'.$auser->id.'">&nbsp;</div>';
e512715b
RW
1487 $teachermodified = '<div id="tt'.$auser->id.'">&nbsp;</div>';
1488 $status = '<div id="st'.$auser->id.'">&nbsp;</div>';
fdb797ad
RW
1489
1490 if ($final_grade->locked or $final_grade->overridden) {
e512715b
RW
1491 $grade = '<div id="g'.$auser->id.'">'.$final_grade->formatted_grade . '</div>';
1492 $hassubmission = true;
1493 } else if ($quickgrade) { // allow editing
fdb797ad
RW
1494 $attributes = array();
1495 $attributes['tabindex'] = $tabindex++;
1496 $menu = html_writer::select(make_grades_menu($this->assignment->grade), 'menu['.$auser->id.']', $auser->grade, array(-1=>get_string('nograde')), $attributes);
e512715b
RW
1497 $grade = '<div id="g'.$auser->id.'">'.$menu.'</div>';
1498 $hassubmission = true;
fdb797ad 1499 } else {
e512715b 1500 $grade = '<div id="g'.$auser->id.'">-</div>';
fdb797ad
RW
1501 }
1502
fdb797ad 1503 if ($final_grade->locked or $final_grade->overridden) {
e512715b 1504 $comment = '<div id="com'.$auser->id.'">'.$final_grade->str_feedback.'</div>';
fdb797ad 1505 } else if ($quickgrade) {
e512715b
RW
1506 $comment = '<div id="com'.$auser->id.'">'
1507 . '<textarea tabindex="'.$tabindex++.'" name="submissioncomment['.$auser->id.']" id="submissioncomment'
1508 . $auser->id.'" rows="2" cols="20">'.($auser->submissioncomment).'</textarea></div>';
fdb797ad 1509 } else {
e512715b 1510 $comment = '<div id="com'.$auser->id.'">&nbsp;</div>';
fdb797ad
RW
1511 }
1512 }
fdb797ad 1513
e512715b
RW
1514 if (empty($auser->status)) { /// Confirm we have exclusively 0 or 1
1515 $auser->status = 0;
fdb797ad 1516 } else {
e512715b 1517 $auser->status = 1;
9bf660b3 1518 }
206ab184 1519
e512715b 1520 $buttontext = ($auser->status == 1) ? $strupdate : $strgrade;
0f7d4e5e 1521
e512715b
RW
1522 ///No more buttons, we use popups ;-).
1523 $popup_url = '/mod/assignment/submissions.php?id='.$this->cm->id
1524 . '&amp;userid='.$auser->id.'&amp;mode=single'.'&amp;filter='.$filter.'&amp;offset='.$offset++;
45fa3412 1525
e512715b 1526 $button = $OUTPUT->action_link($popup_url, $buttontext);
a9573c08 1527
e512715b 1528 $status = '<div id="up'.$auser->id.'" class="s'.$auser->status.'">'.$button.'</div>';
206ab184 1529
e512715b 1530 $finalgrade = '<span id="finalgrade_'.$auser->id.'">'.$final_grade->str_grade.'</span>';
cc03871b 1531
e512715b 1532 $outcomes = '';
5978010d 1533
e512715b 1534 if ($uses_outcomes) {
206ab184 1535
e512715b
RW
1536 foreach($grading_info->outcomes as $n=>$outcome) {
1537 $outcomes .= '<div class="outcome"><label>'.$outcome->name.'</label>';
1538 $options = make_grades_menu(-$outcome->scaleid);
206ab184 1539
e512715b
RW
1540 if ($outcome->grades[$auser->id]->locked or !$quickgrade) {
1541 $options[0] = get_string('nooutcome', 'grades');
1542 $outcomes .= ': <span id="outcome_'.$n.'_'.$auser->id.'">'.$options[$outcome->grades[$auser->id]->grade].'</span>';
1543 } else {
1544 $attributes = array();
1545 $attributes['tabindex'] = $tabindex++;
1546 $attributes['id'] = 'outcome_'.$n.'_'.$auser->id;
1547 $outcomes .= ' '.html_writer::select($options, 'outcome_'.$n.'['.$auser->id.']', $outcome->grades[$auser->id]->grade, array(0=>get_string('nooutcome', 'grades')), $attributes);
1548 }
1549 $outcomes .= '</div>';
fdb797ad 1550 }
cc03871b 1551 }
cc03871b 1552
e512715b 1553 $userlink = '<a href="' . $CFG->wwwroot . '/user/view.php?id=' . $auser->id . '&amp;course=' . $course->id . '">' . fullname($auser, has_capability('moodle/site:viewfullnames', $this->context)) . '</a>';
02dd3b9f 1554 $extradata = array();
1555 foreach ($extrafields as $field) {
1556 $extradata[] = $auser->{$field};
1557 }
1558 $row = array_merge(array($picture, $userlink), $extradata,
1559 array($grade, $comment, $studentmodified, $teachermodified,
1560 $status, $finalgrade));
e512715b
RW
1561 if ($uses_outcomes) {
1562 $row[] = $outcomes;
1563 }
1564 $table->add_data($row);
fdb797ad 1565 }
e512715b 1566 $currentposition++;
fdb797ad 1567 }
54c37fbd
RW
1568 if ($hassubmission && ($this->assignment->assignmenttype=='upload' || $this->assignment->assignmenttype=='online' || $this->assignment->assignmenttype=='uploadsingle')) { //TODO: this is an ugly hack, where is the plugin spirit? (skodak)
1569 echo html_writer::start_tag('div', array('class' => 'mod-assignment-download-link'));
1570 echo html_writer::link(new moodle_url('/mod/assignment/submissions.php', array('id' => $this->cm->id, 'download' => 'zip')), get_string('downloadall', 'assignment'));
1571 echo html_writer::end_tag('div');
1572 }
1573 $table->print_html(); /// Print the whole table
1574 } else {
1575 if ($filter == self::FILTER_SUBMITTED) {
1576 echo html_writer::tag('div', get_string('nosubmisson', 'assignment'), array('class'=>'nosubmisson'));
1577 } else if ($filter == self::FILTER_REQUIRE_GRADING) {
1578 echo html_writer::tag('div', get_string('norequiregrading', 'assignment'), array('class'=>'norequiregrading'));
1579 }
d59269cf 1580 }
b0f2597e 1581 }
45fa3412 1582
fdb797ad 1583 /// Print quickgrade form around the table
e512715b 1584 if ($quickgrade && $table->started_output && !empty($users)){
fdb797ad
RW
1585 $mailinfopref = false;
1586 if (get_user_preferences('assignment_mailinfo', 1)) {
1587 $mailinfopref = true;
1588 }
be34802d 1589 $emailnotification = html_writer::checkbox('mailinfo', 1, $mailinfopref, get_string('enablenotification','assignment'));
de75c481 1590
be34802d 1591 $emailnotification .= $OUTPUT->help_icon('enablenotification', 'assignment');
fdb797ad
RW
1592 echo html_writer::tag('div', $emailnotification, array('class'=>'emailnotification'));
1593
1594 $savefeedback = html_writer::empty_tag('input', array('type'=>'submit', 'name'=>'fastg', 'value'=>get_string('saveallfeedback', 'assignment')));
1595 echo html_writer::tag('div', $savefeedback, array('class'=>'fastgbutton'));
de75c481
RW
1596
1597 echo html_writer::end_tag('form');
fdb797ad 1598 } else if ($quickgrade) {
de75c481 1599 echo html_writer::end_tag('form');
9bf660b3 1600 }
fdb797ad
RW
1601
1602 echo '</div>';
082215e6 1603 /// End of fast grading form
45fa3412 1604
de75c481
RW
1605 /// Mini form for setting user preference
1606
fdb797ad
RW
1607 $formaction = new moodle_url('/mod/assignment/submissions.php', array('id'=>$this->cm->id));
1608 $mform = new MoodleQuickForm('optionspref', 'post', $formaction, '', array('class'=>'optionspref'));
de75c481 1609
fdb797ad
RW
1610 $mform->addElement('hidden', 'updatepref');
1611 $mform->setDefault('updatepref', 1);
1612 $mform->addElement('header', 'qgprefs', get_string('optionalsettings', 'assignment'));
1613 $mform->addElement('select', 'filter', get_string('show'), $filters);
de75c481 1614
fdb797ad
RW
1615 $mform->setDefault('filter', $filter);
1616
1617 $mform->addElement('text', 'perpage', get_string('pagesize', 'assignment'), array('size'=>1));
de75c481 1618 $mform->setDefault('perpage', $perpage);
fdb797ad 1619
9e2eca0f
MG
1620 if ($this->quickgrade_mode_allowed()) {
1621 $mform->addElement('checkbox', 'quickgrade', get_string('quickgrade','assignment'));
1622 $mform->setDefault('quickgrade', $quickgrade);
1623 $mform->addHelpButton('quickgrade', 'quickgrade', 'assignment');
1624 }
de75c481 1625
fdb797ad
RW
1626 $mform->addElement('submit', 'savepreferences', get_string('savepreferences'));
1627
1628 $mform->display();
de75c481 1629
256d2850 1630 echo $OUTPUT->footer();
8e340cb0 1631 }
d699cd1e 1632
18e6298c 1633 /**
36937f02
MG
1634 * If the form was cancelled ('Cancel' or 'Next' was pressed), call cancel method
1635 * from advanced grading (if applicable) and returns true
1636 * If the form was submitted, validates it and returns false if validation did not pass.
18e6298c 1637 * If validation passes, preprocess advanced grading (if applicable) and returns true.
3c2b3cb3
MG
1638 *
1639 * Note to the developers: This is NOT the correct way to implement advanced grading
1640 * in grading form. The assignment grading was written long time ago and unfortunately
1641 * does not fully use the mforms. Usually function is_validated() is called to
1642 * validate the form and get_data() is called to get the data from the form.
1643 *
1644 * Here we have to push the calculated grade to $_POST['xgrade'] because further processing
1645 * of the form gets the data not from form->get_data(), but from $_POST (using statement
1646 * like $feedback = data_submitted() )
18e6298c 1647 */
3c2b3cb3 1648 protected function validate_and_preprocess_feedback() {
71380f2f
MG
1649 global $USER, $CFG;
1650 require_once($CFG->libdir.'/gradelib.php');
36937f02 1651 if (!($feedback = data_submitted()) || !isset($feedback->userid) || !isset($feedback->offset)) {
18e6298c
MG
1652 return true; // No incoming data, nothing to validate
1653 }
1654 $userid = required_param('userid', PARAM_INT);
1655 $offset = required_param('offset', PARAM_INT);
3c2b3cb3
MG
1656 $gradinginfo = grade_get_grades($this->course->id, 'mod', 'assignment', $this->assignment->id, array($userid));
1657 $gradingdisabled = $gradinginfo->items[0]->grades[$userid]->locked || $gradinginfo->items[0]->grades[$userid]->overridden;
71380f2f
MG
1658 if ($gradingdisabled) {
1659 return true;
1660 }
18e6298c
MG
1661 $submissiondata = $this->display_submission($offset, $userid, false);
1662 $mform = $submissiondata->mform;
36937f02
MG
1663 $gradinginstance = $mform->use_advanced_grading();
1664 if (optional_param('cancel', false, PARAM_BOOL) || optional_param('next', false, PARAM_BOOL)) {
1665 // form was cancelled
1666 if ($gradinginstance) {
1667 $gradinginstance->cancel();
1668 }
1669 } else if ($mform->is_submitted()) {
1670 // form was submitted (= a submit button other than 'cancel' or 'next' has been clicked)
18e6298c
MG
1671 if (!$mform->is_validated()) {
1672 return false;
1673 }
1674 // preprocess advanced grading here
36937f02 1675 if ($gradinginstance) {
18e6298c 1676 $data = $mform->get_data();
fc05f222
MG
1677 // create submission if it did not exist yet because we need submission->id for storing the grading instance
1678 $submission = $this->get_submission($userid, true);
1679 $_POST['xgrade'] = $gradinginstance->submit_and_get_grade($data->advancedgrading, $submission->id);
18e6298c
MG
1680 }
1681 }
1682 return true;
1683 }
1684
7af1e882 1685 /**
1686 * Process teacher feedback submission
1687 *
1688 * This is called by submissions() when a grading even has taken place.
1689 * It gets its data from the submitted form.
256578f6 1690 *
1691 * @global object
1692 * @global object
1693 * @global object
1694 * @return object|bool The updated submission object or false
b0f2597e 1695 */
291ee134 1696 function process_feedback($formdata=null) {
f8c81c01 1697 global $CFG, $USER, $DB;
5978010d 1698 require_once($CFG->libdir.'/gradelib.php');
d699cd1e 1699
a19dffc0 1700 if (!$feedback = data_submitted() or !confirm_sesskey()) { // No incoming data?
b0f2597e 1701 return false;
d699cd1e 1702 }
b7b42874 1703
9bf660b3 1704 ///For save and next, we need to know the userid to save, and the userid to go
1705 ///We use a new hidden field in the form, and set it to -1. If it's set, we use this
1706 ///as the userid to store
1707 if ((int)$feedback->saveuserid !== -1){
1708 $feedback->userid = $feedback->saveuserid;
1709 }
1710
b0f2597e 1711 if (!empty($feedback->cancel)) { // User hit cancel button
1712 return false;
1713 }
d699cd1e 1714
5978010d 1715 $grading_info = grade_get_grades($this->course->id, 'mod', 'assignment', $this->assignment->id, $feedback->userid);
1716
cc03871b 1717 // store outcomes if needed
1718 $this->process_outcomes($feedback->userid);
1719
7af1e882 1720 $submission = $this->get_submission($feedback->userid, true); // Get or make one
d699cd1e 1721
d2b6ee29 1722 if (!($grading_info->items[0]->grades[$feedback->userid]->locked ||
1723 $grading_info->items[0]->grades[$feedback->userid]->overridden) ) {
d699cd1e 1724
d2b6ee29 1725 $submission->grade = $feedback->xgrade;
1726 $submission->submissioncomment = $feedback->submissioncomment_editor['text'];
5978010d 1727 $submission->teacher = $USER->id;
2dc5d980 1728 $mailinfo = get_user_preferences('assignment_mailinfo', 0);
1729 if (!$mailinfo) {
1730 $submission->mailed = 1; // treat as already mailed
1731 } else {
1732 $submission->mailed = 0; // Make sure mail goes out (again, even)
1733 }
5978010d 1734 $submission->timemarked = time();
d4156e80 1735
5978010d 1736 unset($submission->data1); // Don't need to update this.
1737 unset($submission->data2); // Don't need to update this.
d699cd1e 1738
5978010d 1739 if (empty($submission->timemodified)) { // eg for offline assignments
1740 // $submission->timemodified = time();
1741 }
d699cd1e 1742
0bcf8b6f 1743 $DB->update_record('assignment_submissions', $submission);
7bddd4b7 1744
5978010d 1745 // triger grade event
1746 $this->update_grade($submission);
1747
1748 add_to_log($this->course->id, 'assignment', 'update grades',
0f66aced 1749 'submissions.php?id='.$this->cm->id.'&user='.$feedback->userid, $feedback->userid, $this->cm->id);
291ee134
AB
1750 if (!is_null($formdata)) {
1751 if ($this->type == 'upload' || $this->type == 'uploadsingle') {
1752 $mformdata = $formdata->mform->get_data();
1753 $mformdata = file_postupdate_standard_filemanager($mformdata, 'files', $formdata->fileui_options, $this->context, 'mod_assignment', 'response', $submission->id);
1754 }
1755 }
5978010d 1756 }
45fa3412 1757
7af1e882 1758 return $submission;
d699cd1e 1759
d699cd1e 1760 }
d699cd1e 1761
cc03871b 1762 function process_outcomes($userid) {
1763 global $CFG, $USER;
fbaa56b2 1764
1765 if (empty($CFG->enableoutcomes)) {
1766 return;
1767 }
1768
cc03871b 1769 require_once($CFG->libdir.'/gradelib.php');
1770
a19dffc0 1771 if (!$formdata = data_submitted() or !confirm_sesskey()) {
cc03871b 1772 return;
1773 }
1774
1775 $data = array();
fcac8e51 1776 $grading_info = grade_get_grades($this->course->id, 'mod', 'assignment', $this->assignment->id, $userid);
1777
1778 if (!empty($grading_info->outcomes)) {
d886a7ea 1779 foreach($grading_info->outcomes as $n=>$old) {
1780 $name = 'outcome_'.$n;
1781 if (isset($formdata->{$name}[$userid]) and $old->grades[$userid]->grade != $formdata->{$name}[$userid]) {
1782 $data[$n] = $formdata->{$name}[$userid];
cc03871b 1783 }
1784 }
1785 }
1786 if (count($data) > 0) {
1787 grade_update_outcomes('mod/assignment', $this->course->id, 'mod', 'assignment', $this->assignment->id, $userid, $data);
1788 }
1789
1790 }
1791
7af1e882 1792 /**
1793 * Load the submission object for a particular user
1794 *
256578f6 1795 * @global object
1796 * @global object
7af1e882 1797 * @param $userid int The id of the user whose submission we want or 0 in which case USER->id is used
1798 * @param $createnew boolean optional Defaults to false. If set to true a new submission object will be created in the database
03076be4 1799 * @param bool $teachermodified student submission set if false
7af1e882 1800 * @return object The submission
1801 */
03076be4 1802 function get_submission($userid=0, $createnew=false, $teachermodified=false) {
5053f00f 1803 global $USER, $DB;
f77cfb73 1804
1805 if (empty($userid)) {
1806 $userid = $USER->id;
1807 }
1808
5053f00f 1809 $submission = $DB->get_record('assignment_submissions', array('assignment'=>$this->assignment->id, 'userid'=>$userid));
d699cd1e 1810
b0f2597e 1811 if ($submission || !$createnew) {
1812 return $submission;
1813 }
03076be4 1814 $newsubmission = $this->prepare_new_submission($userid, $teachermodified);
7826abc7 1815 $DB->insert_record("assignment_submissions", $newsubmission);
d699cd1e 1816
5053f00f 1817 return $DB->get_record('assignment_submissions', array('assignment'=>$this->assignment->id, 'userid'=>$userid));
b0f2597e 1818 }
d699cd1e 1819
7af1e882 1820 /**
1821 * Instantiates a new submission object for a given user
1822 *
1823 * Sets the assignment, userid and times, everything else is set to default values.
256578f6 1824 *
1825 * @param int $userid The userid for which we want a submission object
03076be4 1826 * @param bool $teachermodified student submission set if false
7af1e882 1827 * @return object The submission
1828 */
03076be4 1829 function prepare_new_submission($userid, $teachermodified=false) {
39790bd8 1830 $submission = new stdClass();
39e11905 1831 $submission->assignment = $this->assignment->id;
1832 $submission->userid = $userid;
47c96a77 1833 $submission->timecreated = time();
16fc2088 1834 // teachers should not be modifying modified date, except offline assignments
03076be4 1835 if ($teachermodified) {
1836 $submission->timemodified = 0;
1837 } else {
1838 $submission->timemodified = $submission->timecreated;
1839 }
39e11905 1840 $submission->numfiles = 0;
1841 $submission->data1 = '';
1842 $submission->data2 = '';
1843 $submission->grade = -1;
ea6432fe 1844 $submission->submissioncomment = '';
39e11905 1845 $submission->format = 0;
1846 $submission->teacher = 0;
1847 $submission->timemarked = 0;
1848 $submission->mailed = 0;
1849 return $submission;
1850 }
1851
7af1e882 1852 /**
1853 * Return all assignment submissions by ENROLLED students (even empty)
1854 *
256578f6 1855 * @param string $sort optional field names for the ORDER BY in the sql query
1856 * @param string $dir optional specifying the sort direction, defaults to DESC
7af1e882 1857 * @return array The submission objects indexed by id
1858 */
b0f2597e 1859 function get_submissions($sort='', $dir='DESC') {
7af1e882 1860 return assignment_get_all_submissions($this->assignment, $sort, $dir);
b0f2597e 1861 }
1862
7af1e882 1863 /**
1864 * Counts all real assignment submissions by ENROLLED students (not empty ones)
1865 *
256578f6 1866 * @param int $groupid optional If nonzero then count is restricted to this group
7af1e882 1867 * @return int The number of submissions
1868 */
b0f2597e 1869 function count_real_submissions($groupid=0) {
dd97c328 1870 return assignment_count_real_submissions($this->cm, $groupid);
d59269cf 1871 }
d699cd1e 1872
7af1e882 1873 /**
1874 * Alerts teachers by email of new or changed assignments that need grading
1875 *
1876 * First checks whether the option to email teachers is set for this assignment.
1877 * Sends an email to ALL teachers in the course (or in the group if using separate groups).
1878 * Uses the methods email_teachers_text() and email_teachers_html() to construct the content.
256578f6 1879 *
1880 * @global object
1881 * @global object
7af1e882 1882 * @param $submission object The submission that has changed
256578f6 1883 * @return void
7af1e882 1884 */
73097f07 1885 function email_teachers($submission) {
5053f00f 1886 global $CFG, $DB;
73097f07 1887
d8199f1d 1888 if (empty($this->assignment->emailteachers)) { // No need to do anything
73097f07 1889 return;
1890 }
1891
5053f00f 1892 $user = $DB->get_record('user', array('id'=>$submission->userid));
73097f07 1893
413efd22 1894 if ($teachers = $this->get_graders($user)) {
73097f07 1895
1896 $strassignments = get_string('modulenameplural', 'assignment');
1897 $strassignment = get_string('modulename', 'assignment');
1898 $strsubmitted = get_string('submitted', 'assignment');
1899
1900 foreach ($teachers as $teacher) {
39790bd8 1901 $info = new stdClass();
413efd22 1902 $info->username = fullname($user, true);
d8199f1d 1903 $info->assignment = format_string($this->assignment->name,true);
1904 $info->url = $CFG->wwwroot.'/mod/assignment/submissions.php?id='.$this->cm->id;
92d0dd9f 1905 $info->timeupdated = userdate($submission->timemodified, '%c', $teacher->timezone);
d8199f1d 1906
1907 $postsubject = $strsubmitted.': '.$info->username.' -> '.$this->assignment->name;
1908 $posttext = $this->email_teachers_text($info);
1909 $posthtml = ($teacher->mailformat == 1) ? $this->email_teachers_html($info) : '';
73097f07 1910
39790bd8 1911 $eventdata = new stdClass();
3b120e46 1912 $eventdata->modulename = 'assignment';
1913 $eventdata->userfrom = $user;
1914 $eventdata->userto = $teacher;
1915 $eventdata->subject = $postsubject;
1916 $eventdata->fullmessage = $posttext;
1917 $eventdata->fullmessageformat = FORMAT_PLAIN;
1918 $eventdata->fullmessagehtml = $posthtml;
fa09b5a9 1919 $eventdata->smallmessage = $postsubject;
192bcd76 1920
39e171ac 1921 $eventdata->name = 'assignment_updates';
192bcd76 1922 $eventdata->component = 'mod_assignment';
39e171ac 1923 $eventdata->notification = 1;
6217809c
AB
1924 $eventdata->contexturl = $info->url;
1925 $eventdata->contexturlname = $info->assignment;
54c37fbd 1926
7c7d3afa 1927 message_send($eventdata);
73097f07 1928 }
1929 }
1930 }
1931
256578f6 1932 /**
1933 * @param string $filearea
1934 * @param array $args
1935 * @return bool
1936 */
172dd12c 1937 function send_file($filearea, $args) {
1938 debugging('plugin does not implement file sending', DEBUG_DEVELOPER);
1939 return false;
1940 }
1941
413efd22 1942 /**
1943 * Returns a list of teachers that should be grading given submission
256578f6 1944 *
1945 * @param object $user
1946 * @return array
413efd22 1947 */
1948 function get_graders($user) {
1949 //potential graders
7bddd4b7 1950 $potgraders = get_users_by_capability($this->context, 'mod/assignment:grade', '', '', '', '', '', '', false, false);
1951
413efd22 1952 $graders = array();
ba3dc7b4 1953 if (groups_get_activity_groupmode($this->cm) == SEPARATEGROUPS) { // Separate groups are being used
2c386f82 1954 if ($groups = groups_get_all_groups($this->course->id, $user->id)) { // Try to find all groups
413efd22 1955 foreach ($groups as $group) {
1956 foreach ($potgraders as $t) {
1957 if ($t->id == $user->id) {
1958 continue; // do not send self
1959 }
1960 if (groups_is_member($group->id, $t->id)) {
1961 $graders[$t->id] = $t;
1962 }
1963 }
1964 }
1965 } else {
1966 // user not in group, try to find graders without group
1967 foreach ($potgraders as $t) {
1968 if ($t->id == $user->id) {
1969 continue; // do not send self
1970 }
2c386f82 1971 if (!groups_get_all_groups($this->course->id, $t->id)) { //ugly hack
413efd22 1972 $graders[$t->id] = $t;
1973 }
1974 }
1975 }
1976 } else {
1977 foreach ($potgraders as $t) {
1978 if ($t->id == $user->id) {
1979 continue; // do not send self
1980 }
1981 $graders[$t->id] = $t;
1982 }
1983 }
1984 return $graders;
1985 }
1986
7af1e882 1987 /**
1988 * Creates the text content for emails to teachers
1989 *
1990 * @param $info object The info used by the 'emailteachermail' language string
1991 * @return string
1992 */
d8199f1d 1993 function email_teachers_text($info) {
8ebbb06a
SH
1994 $posttext = format_string($this->course->shortname, true, array('context' => $this->coursecontext)).' -> '.
1995 $this->strassignments.' -> '.
1996 format_string($this->assignment->name, true, array('context' => $this->context))."\n";
d8199f1d 1997 $posttext .= '---------------------------------------------------------------------'."\n";
1998 $posttext .= get_string("emailteachermail", "assignment", $info)."\n";
73963212 1999 $posttext .= "\n---------------------------------------------------------------------\n";
d8199f1d 2000 return $posttext;
2001 }
2002
7af1e882 2003 /**
2004 * Creates the html content for emails to teachers
2005 *
2006 * @param $info object The info used by the 'emailteachermailhtml' language string
2007 * @return string
2008 */
d8199f1d 2009 function email_teachers_html($info) {
3554b5c2 2010 global $CFG;
d8199f1d 2011 $posthtml = '<p><font face="sans-serif">'.
8ebbb06a 2012 '<a href="'.$CFG->wwwroot.'/course/view.php?id='.$this->course->id.'">'.format_string($this->course->shortname, true, array('context' => $this->coursecontext)).'</a> ->'.
d8199f1d 2013 '<a href="'.$CFG->wwwroot.'/mod/assignment/index.php?id='.$this->course->id.'">'.$this->strassignments.'</a> ->'.
8ebbb06a 2014 '<a href="'.$CFG->wwwroot.'/mod/assignment/view.php?id='.$this->cm->id.'">'.format_string($this->assignment->name, true, array('context' => $this->context)).'</a></font></p>';
d8199f1d 2015 $posthtml .= '<hr /><font face="sans-serif">';
2016 $posthtml .= '<p>'.get_string('emailteachermailhtml', 'assignment', $info).'</p>';
2017 $posthtml .= '</font><hr />';
815b5ca6 2018 return $posthtml;
d8199f1d 2019 }
2020
7af1e882 2021 /**
2022 * Produces a list of links to the files uploaded by a user
2023 *
2024 * @param $userid int optional id of the user. If 0 then $USER->id is used.
2025 * @param $return boolean optional defaults to false. If true the list is returned rather than printed
2026 * @return string optional
2027 */
d8199f1d 2028 function print_user_files($userid=0, $return=false) {
d436d197 2029 global $CFG, $USER, $OUTPUT;
45fa3412 2030
d8199f1d 2031 if (!$userid) {
2032 if (!isloggedin()) {
2033 return '';
2034 }
2035 $userid = $USER->id;
2036 }
45fa3412 2037
73097f07 2038 $output = '';
45fa3412 2039
31f56ef6 2040 $submission = $this->get_submission($userid);
6708a1f5
SH
2041 if (!$submission) {
2042 return $output;
2043 }
31f56ef6 2044
6708a1f5
SH
2045 $fs = get_file_storage();
2046 $files = $fs->get_area_files($this->context->id, 'mod_assignment', 'submission', $submission->id, "timemodified", false);
2047 if (!empty($files)) {
24ba58ee 2048 require_once($CFG->dirroot . '/mod/assignment/locallib.php');
6708a1f5
SH
2049 if ($CFG->enableportfolios) {
2050 require_once($CFG->libdir.'/portfoliolib.php');
2051 $button = new portfolio_add_button();
2052 }
172dd12c 2053 foreach ($files as $file) {
2054 $filename = $file->get_filename();
172dd12c 2055 $mimetype = $file->get_mimetype();
437239d1 2056 $path = file_encode_url($CFG->wwwroot.'/pluginfile.php', '/'.$this->context->id.'/mod_assignment/submission/'.$submission->id.'/'.$filename);
b5d0cafc 2057 $output .= '<a href="'.$path.'" ><img src="'.$OUTPUT->pix_url(file_mimetype_icon($mimetype)).'" class="icon" alt="'.$mimetype.'" />'.s($filename).'</a>';
6708a1f5 2058 if ($CFG->enableportfolios && $this->portfolio_exportable() && has_capability('mod/assignment:exportownsubmission', $this->context)) {
fd04c5bd 2059 $button->set_callback_options('assignment_portfolio_caller', array('id' => $this->cm->id, 'submissionid' => $submission->id, 'fileid' => $file->get_id()), '/mod/assignment/locallib.php');
887160c7 2060 $button->set_format_by_file($file);
0d06b6fd 2061 $output .= $button->to_html(PORTFOLIO_ADD_ICON_LINK);
73097f07 2062 }
c676af9f 2063
19f7391c
SB
2064 if ($CFG->enableplagiarism) {
2065 require_once($CFG->libdir.'/plagiarismlib.php');
2066 $output .= plagiarism_get_links(array('userid'=>$userid, 'file'=>$file, 'cmid'=>$this->cm->id, 'course'=>$this->course, 'assignment'=>$this->assignment));
2067 $output .= '<br />';
2068 }
172dd12c 2069 }
6057bf5b 2070 if ($CFG->enableportfolios && count($files) > 1 && $this->portfolio_exportable() && has_capability('mod/assignment:exportownsubmission', $this->context)) {
fd04c5bd 2071 $button->set_callback_options('assignment_portfolio_caller', array('id' => $this->cm->id, 'submissionid' => $submission->id), '/mod/assignment/locallib.php');
b777c798 2072 $output .= '<br />' . $button->to_html(PORTFOLIO_ADD_TEXT_LINK);
73097f07 2073 }
2074 }
2075
2076 $output = '<div class="files">'.$output.'</div>';
2077
2078 if ($return) {
2079 return $output;
2080 }
2081 echo $output;
2082 }
2083
7af1e882 2084 /**
2085 * Count the files uploaded by a given user
2086 *
b5e1ffe4 2087 * @param $itemid int The submission's id as the file's itemid.
7af1e882 2088 * @return int
2089 */
b5e1ffe4 2090 function count_user_files($itemid) {
172dd12c 2091 $fs = get_file_storage();
b5e1ffe4 2092 $files = $fs->get_area_files($this->context->id, 'mod_assignment', 'submission', $itemid, "id", false);
172dd12c 2093 return count($files);
73097f07 2094 }
2095
7af1e882 2096 /**
2097 * Returns true if the student is allowed to submit
2098 *
2099 * Checks that the assignment has started and, if the option to prevent late
2100 * submissions is set, also checks that the assignment has not yet closed.
2101 * @return boolean
2102 */
f77cfb73 2103 function isopen() {
2104 $time = time();
1e4343a0 2105 if ($this->assignment->preventlate && $this->assignment->timedue) {
f77cfb73 2106 return ($this->assignment->timeavailable <= $time && $time <= $this->assignment->timedue);
2107 } else {
2108 return ($this->assignment->timeavailable <= $time);
2109 }
2110 }
2111
0b5a80a1 2112
2113 /**
dc6cb74e 2114 * Return true if is set description is hidden till available date
2115 *
0b5a80a1 2116 * This is needed by calendar so that hidden descriptions do not
dc6cb74e 2117 * come up in upcoming events.
2118 *
0b5a80a1 2119 * Check that description is hidden till available date
dc6cb74e 2120 * By default return false
2121 * Assignments types should implement this method if needed
2122 * @return boolen
0b5a80a1 2123 */
dc6cb74e 2124 function description_is_hidden() {
2125 return false;
2126 }
2127
7af1e882 2128 /**
2129 * Return an outline of the user's interaction with the assignment
2130 *
2131 * The default method prints the grade and timemodified
1a96363a 2132 * @param $grade object
7af1e882 2133 * @return object with properties ->info and ->time
2134 */
1a96363a 2135 function user_outline($grade) {
39e11905 2136
39790bd8 2137 $result = new stdClass();
1a96363a
NC
2138 $result->info = get_string('grade').': '.$grade->str_long_grade;
2139 $result->time = $grade->dategraded;
2140 return $result;
73097f07 2141 }
7af1e882 2142
2143 /**
2144 * Print complete information about the user's interaction with the assignment
2145 *
2146 * @param $user object
2147 */
1a96363a 2148 function user_complete($user, $grade=null) {
3a003ead 2149 global $OUTPUT;
1a96363a 2150
73097f07 2151 if ($submission = $this->get_submission($user->id)) {
172dd12c 2152
2153 $fs = get_file_storage();
26a9dc72 2154
87f702a0 2155 if ($files = $fs->get_area_files($this->context->id, 'mod_assignment', 'submission', $submission->id, "timemodified", false)) {
172dd12c 2156 $countfiles = count($files)." ".get_string("uploadedfiles", "assignment");
2157 foreach ($files as $file) {
2158 $countfiles .= "; ".$file->get_filename();
73097f07 2159 }
2160 }
45fa3412 2161
3a003ead 2162 echo $OUTPUT->box_start();
73097f07 2163 echo get_string("lastmodified").": ";
9bf660b3 2164 echo userdate($submission->timemodified);
2165 echo $this->display_lateness($submission->timemodified);
45fa3412 2166
70b2c772 2167 $this->print_user_files($user->id);
45fa3412 2168
73097f07 2169 echo '<br />';
45fa3412 2170
1a96363a 2171 $this->view_feedback($submission);
45fa3412 2172
3a003ead 2173 echo $OUTPUT->box_end();
45fa3412 2174
73097f07 2175 } else {
156d6f48
MG
2176 if ($grade) {
2177 echo $OUTPUT->container(get_string('grade').': '.$grade->str_long_grade);
2178 if ($grade->str_feedback) {
2179 echo $OUTPUT->container(get_string('feedback').': '.$grade->str_feedback);
2180 }
2181 }
73097f07 2182 print_string("notsubmittedyet", "assignment");
2183 }
2184 }
2185
7af1e882 2186 /**
2187 * Return a string indicating how late a submission is
2188 *
45fa3412 2189 * @param $timesubmitted int
7af1e882 2190 * @return string
2191 */
70b2c772 2192 function display_lateness($timesubmitted) {
76a60031 2193 return assignment_display_lateness($timesubmitted, $this->assignment->timedue);
73097f07 2194 }
2195
55b4d096 2196 /**
2197 * Empty method stub for all delete actions.
2198 */
2199 function delete() {
2200 //nothing by default
2201 redirect('view.php?id='.$this->cm->id);
2202 }
2203
2204 /**
2205 * Empty custom feedback grading form.
2206 */
2207 function custom_feedbackform($submission, $return=false) {
2208 //nothing by default
2209 return '';
2210 }
73097f07 2211
09ba8e56 2212 /**
2213 * Add a get_coursemodule_info function in case any assignment type wants to add 'extra' information
2214 * for the course (see resource).
2215 *
206ab184 2216 * Given a course_module object, this function returns any "extra" information that may be needed
09ba8e56 2217 * when printing this activity in a course listing. See get_array_of_activities() in course/lib.php.
206ab184 2218 *
09ba8e56 2219 * @param $coursemodule object The coursemodule object (record).
3e4c2435 2220 * @return cached_cm_info Object used to customise appearance on course page
09ba8e56 2221 */
2222 function get_coursemodule_info($coursemodule) {
3e4c2435 2223 return null;
09ba8e56 2224 }
2225
d014b69b 2226 /**
2227 * Plugin cron method - do not use $this here, create new assignment instances if needed.
2228 * @return void
2229 */
2230 function cron() {
2231 //no plugin cron by default - override if needed
2232 }
2233
0b5a80a1 2234 /**
2235 * Reset all submissions
2236 */
2237 function reset_userdata($data) {
5053f00f 2238 global $CFG, $DB;
0b5a80a1 2239
74d7d735 2240 if (!$DB->count_records('assignment', array('course'=>$data->courseid, 'assignmenttype'=>$this->type))) {
0b5a80a1 2241 return array(); // no assignments of this type present
2242 }
2243
2244 $componentstr = get_string('modulenameplural', 'assignment');
2245 $status = array();
2246
2247 $typestr = get_string('type'.$this->type, 'assignment');
40fcf70c
DP
2248 // ugly hack to support pluggable assignment type titles...
2249 if($typestr === '[[type'.$this->type.']]'){
2250 $typestr = get_string('type'.$this->type, 'assignment_'.$this->type);
2251 }
0b5a80a1 2252
2253 if (!empty($data->reset_assignment_submissions)) {
2254 $assignmentssql = "SELECT a.id
5053f00f 2255 FROM {assignment} a
2256 WHERE a.course=? AND a.assignmenttype=?";
2257 $params = array($data->courseid, $this->type);
0b5a80a1 2258
75dfe830 2259 // now get rid of all submissions and responses
4e866d5e 2260 $fs = get_file_storage();
5053f00f 2261 if ($assignments = $DB->get_records_sql($assignmentssql, $params)) {
0b5a80a1 2262 foreach ($assignments as $assignmentid=>$unused) {
4e866d5e 2263 if (!$cm = get_coursemodule_from_instance('assignment', $assignmentid)) {
2264 continue;
2265 }
2266 $context = get_context_instance(CONTEXT_MODULE, $cm->id);
64f93798
PS
2267 $fs->delete_area_files($context->id, 'mod_assignment', 'submission');
2268 $fs->delete_area_files($context->id, 'mod_assignment', 'response');
0b5a80a1 2269 }
2270 }
2271
75dfe830 2272 $DB->delete_records_select('assignment_submissions', "assignment IN ($assignmentssql)", $params);
2273
0b5a80a1 2274 $status[] = array('component'=>$componentstr, 'item'=>get_string('deleteallsubmissions','assignment').': '.$typestr, 'error'=>false);
dd97c328 2275
0b5a80a1 2276 if (empty($data->reset_gradebook_grades)) {
2277 // remove all grades from gradebook
2278 assignment_reset_gradebook($data->courseid, $this->type);
2279 }
2280 }
2281
2282 /// updating dates - shift may be negative too
2283 if ($data->timeshift) {
2284 shift_course_mod_dates('assignment', array('timedue', 'timeavailable'), $data->timeshift, $data->courseid);
2285 $status[] = array('component'=>$componentstr, 'item'=>get_string('datechanged').': '.$typestr, 'error'=>false);
2286 }
2287
2288 return $status;
2289 }
67a87e7d 2290
2291
2292 function portfolio_exportable() {
2293 return false;
2294 }
3b804d2d 2295
2296 /**
2297 * base implementation for backing up subtype specific information
2298 * for one single module
2299 *
2300 * @param filehandle $bf file handle for xml file to write to
2301 * @param mixed $preferences the complete backup preference object
2302 *
2303 * @return boolean
2304 *
2305 * @static
2306 */
2307 static function backup_one_mod($bf, $preferences, $assignment) {
2308 return true;
2309 }
2310
2311 /**
2312 * base implementation for backing up subtype specific information
2313 * for one single submission
2314 *
2315 * @param filehandle $bf file handle for xml file to write to
2316 * @param mixed $preferences the complete backup preference object
2317 * @param object $submission the assignment submission db record
2318 *
2319 * @return boolean
2320 *
2321 * @static
2322 */
2323 static function backup_one_submission($bf, $preferences, $assignment, $submission) {
2324 return true;
2325 }
2326
2327 /**
2328 * base implementation for restoring subtype specific information
2329 * for one single module
2330 *
2331 * @param array $info the array representing the xml
2332 * @param object $restore the restore preferences
2333 *
2334 * @return boolean
2335 *
2336 * @static
2337 */
2338 static function restore_one_mod($info, $restore, $assignment) {
2339 return true;
2340 }
2341
2342 /**
2343 * base implementation for restoring subtype specific information
2344 * for one single submission
2345 *
2346 * @param object $submission the newly created submission
2347 * @param array $info the array representing the xml
2348 * @param object $restore the restore preferences
2349 *
2350 * @return boolean
2351 *
2352 * @static
2353 */
2354 static function restore_one_submission($info, $restore, $assignment, $submission) {
2355 return true;
2356 }
2357
b0f2597e 2358} ////// End of the assignment_base class
d699cd1e 2359
04eba58f 2360
7efcb735 2361class mod_assignment_grading_form extends moodleform {
3c2b3cb3
MG
2362 /** @var stores the advaned grading instance (if used in grading) */
2363 private $advancegradinginstance;
d2b6ee29 2364
2365 function definition() {
2366 global $OUTPUT;
2367 $mform =& $this->_form;
2368
36937f02
MG
2369 if (isset($this->_customdata->advancedgradinginstance)) {
2370 $this->use_advanced_grading($this->_customdata->advancedgradinginstance);
18e6298c
MG
2371 }
2372
d2b6ee29 2373 $formattr = $mform->getAttributes();
2374 $formattr['id'] = 'submitform';
2375 $mform->setAttributes($formattr);
2376 // hidden params
2377 $mform->addElement('hidden', 'offset', ($this->_customdata->offset+1));
2378 $mform->setType('offset', PARAM_INT);
2379 $mform->addElement('hidden', 'userid', $this->_customdata->userid);
2380 $mform->setType('userid', PARAM_INT);
2381 $mform->addElement('hidden', 'nextid', $this->_customdata->nextid);
2382 $mform->setType('nextid', PARAM_INT);
2383 $mform->addElement('hidden', 'id', $this->_customdata->cm->id);
2384 $mform->setType('id', PARAM_INT);
2385 $mform->addElement('hidden', 'sesskey', sesskey());
2386 $mform->setType('sesskey', PARAM_ALPHANUM);
2387 $mform->addElement('hidden', 'mode', 'grade');
2d274675 2388 $mform->setType('mode', PARAM_TEXT);
d2b6ee29 2389 $mform->addElement('hidden', 'menuindex', "0");
2390 $mform->setType('menuindex', PARAM_INT);
2391 $mform->addElement('hidden', 'saveuserid', "-1");
2392 $mform->setType('saveuserid', PARAM_INT);
fdb797ad
RW
2393 $mform->addElement('hidden', 'filter', "0");
2394 $mform->setType('filter', PARAM_INT);
d2b6ee29 2395
2396 $mform->addElement('static', 'picture', $OUTPUT->user_picture($this->_customdata->user),
2397 fullname($this->_customdata->user, true) . '<br/>' .
2398 userdate($this->_customdata->submission->timemodified) .
2399 $this->_customdata->lateness );
2400
291ee134 2401 $this->add_submission_content();
d2b6ee29 2402 $this->add_grades_section();
2403
2404 $this->add_feedback_section();
2405
261b585d 2406 if ($this->_customdata->submission->timemarked) {
291ee134 2407 $datestring = userdate($this->_customdata->submission->timemarked)."&nbsp; (".format_time(time() - $this->_customdata->submission->timemarked).")";
d2b6ee29 2408 $mform->addElement('header', 'Last Grade', get_string('lastgrade', 'assignment'));
2409 $mform->addElement('static', 'picture', $OUTPUT->user_picture($this->_customdata->teacher) ,
2410 fullname($this->_customdata->teacher,true).
291ee134 2411 '<br/>'.$datestring);
d2b6ee29 2412 }
2413 // buttons
2414 $this->add_action_buttons();
2415
d2b6ee29 2416 }
2417
18e6298c 2418 /**
36937f02 2419 * Gets or sets the instance for advanced grading
18e6298c 2420 *
36937f02 2421 * @param gradingform_instance $gradinginstance
18e6298c 2422 */
36937f02
MG
2423 public function use_advanced_grading($gradinginstance = false) {
2424 if ($gradinginstance !== false) {
2425 $this->advancegradinginstance = $gradinginstance;
18e6298c 2426 }
36937f02 2427 return $this->advancegradinginstance;
18e6298c
MG
2428 }
2429
d2b6ee29 2430 function add_grades_section() {
2431 global $CFG;
2432 $mform =& $this->_form;
2433 $attributes = array();
261b585d 2434 if ($this->_customdata->gradingdisabled) {
2435 $attributes['disabled'] ='disabled';
2436 }
d2b6ee29 2437
d2b6ee29 2438 $mform->addElement('header', 'Grades', get_string('grades', 'grades'));
fba356f3 2439
d2b6ee29 2440 $grademenu = make_grades_menu($this->_customdata->assignment->grade);
36937f02 2441 if ($gradinginstance = $this->use_advanced_grading()) {
9e2eca0f 2442 $gradinginstance->get_controller()->set_grade_range($grademenu);
71380f2f
MG
2443 $gradingelement = $mform->addElement('grading', 'advancedgrading', get_string('grade').':', array('gradinginstance' => $gradinginstance));
2444 if ($this->_customdata->gradingdisabled) {
2445 $gradingelement->freeze();
2446 } else {
2447 $mform->addElement('hidden', 'advancedgradinginstanceid', $gradinginstance->get_id());
2448 }
fba356f3
DM
2449 } else {
2450 // use simple direct grading
fba356f3 2451 $grademenu['-1'] = get_string('nograde');
d2b6ee29 2452
fba356f3
DM
2453 $mform->addElement('select', 'xgrade', get_string('grade').':', $grademenu, $attributes);
2454 $mform->setDefault('xgrade', $this->_customdata->submission->grade ); //@fixme some bug when element called 'grade' makes it break
2455 $mform->setType('xgrade', PARAM_INT);
2456 }
d2b6ee29 2457
261b585d 2458 if (!empty($this->_customdata->enableoutcomes)) {
d2b6ee29 2459 foreach($this->_customdata->grading_info->outcomes as $n=>$outcome) {
2460 $options = make_grades_menu(-$outcome->scaleid);
2461 if ($outcome->grades[$this->_customdata->submission->userid]->locked) {
2462 $options[0] = get_string('nooutcome', 'grades');
8545f86c
MG
2463 $mform->addElement('static', 'outcome_'.$n.'['.$this->_customdata->userid.']', $outcome->name.':',
2464 $options[$outcome->grades[$this->_customdata->submission->userid]->grade]);
d2b6ee29 2465 } else {
2466 $options[''] = get_string('nooutcome', 'grades');
2467 $attributes = array('id' => 'menuoutcome_'.$n );
2468 $mform->addElement('select', 'outcome_'.$n.'['.$this->_customdata->userid.']', $outcome->name.':', $options, $attributes );
2469 $mform->setType('outcome_'.$n.'['.$this->_customdata->userid.']', PARAM_INT);
2470 $mform->setDefault('outcome_'.$n.'['.$this->_customdata->userid.']', $outcome->grades[$this->_customdata->submission->userid]->grade );
2471 }
2472 }
2473 }
753c1de5 2474 $course_context = get_context_instance(CONTEXT_MODULE , $this->_customdata->cm->id);
2475 if (has_capability('gradereport/grader:view', $course_context) && has_capability('moodle/grade:viewall', $course_context)) {
2476 $grade = '<a href="'.$CFG->wwwroot.'/grade/report/grader/index.php?id='. $this->_customdata->courseid .'" >'.
2477 $this->_customdata->grading_info->items[0]->grades[$this->_customdata->userid]->str_grade . '</a>';
2478 }else{
2479 $grade = $this->_customdata->grading_info->items[0]->grades[$this->_customdata->userid]->str_grade;
2480 }
2481 $mform->addElement('static', 'finalgrade', get_string('currentgrade', 'assignment').':' ,$grade);
d2b6ee29 2482 $mform->setType('finalgrade', PARAM_INT);
2483 }
2484
2485 /**
2486 *
2487 * @global core_renderer $OUTPUT
2488 */
2489 function add_feedback_section() {
2490 global $OUTPUT;
2491 $mform =& $this->_form;
2492 $mform->addElement('header', 'Feed Back', get_string('feedback', 'grades'));
2493
261b585d 2494 if ($this->_customdata->gradingdisabled) {
d2b6ee29 2495 $mform->addElement('static', 'disabledfeedback', $this->_customdata->grading_info->items[0]->grades[$this->_customdata->userid]->str_feedback );
2496 } else {
2497 // visible elements
2498
2499 $mform->addElement('editor', 'submissioncomment_editor', get_string('feedback', 'assignment').':', null, $this->get_editor_options() );
2500 $mform->setType('submissioncomment_editor', PARAM_RAW); // to be cleaned before display
2501 $mform->setDefault('submissioncomment_editor', $this->_customdata->submission->submissioncomment);
2502 //$mform->addRule('submissioncomment', get_string('required'), 'required', null, 'client');
291ee134
AB
2503 switch ($this->_customdata->assignment->assignmenttype) {
2504 case 'upload' :
2505 case 'uploadsingle' :
2506 $mform->addElement('filemanager', 'files_filemanager', get_string('responsefiles', 'assignment'). ':', null, $this->_customdata->fileui_options);
2507 break;
2508 default :
2509 break;
2510 }
d2b6ee29 2511 $mform->addElement('hidden', 'mailinfo_h', "0");
2512 $mform->setType('mailinfo_h', PARAM_INT);
be34802d
AD
2513 $mform->addElement('checkbox', 'mailinfo',get_string('enablenotification','assignment').
2514 $OUTPUT->help_icon('enablenotification', 'assignment') .':' );
d2b6ee29 2515 $mform->setType('mailinfo', PARAM_INT);
2516 }
2517 }
2518
2519 function add_action_buttons() {
2520 $mform =& $this->_form;
d2b6ee29 2521 //if there are more to be graded.
261b585d 2522 if ($this->_customdata->nextid>0) {
d2b6ee29 2523 $buttonarray=array();
2524 $buttonarray[] = &$mform->createElement('submit', 'submitbutton', get_string('savechanges'));
2525 //@todo: fix accessibility: javascript dependency not necessary
2526 $buttonarray[] = &$mform->createElement('submit', 'saveandnext', get_string('saveandnext'));
2527 $buttonarray[] = &$mform->createElement('submit', 'next', get_string('next'));
2528 $buttonarray[] = &$mform->createElement('cancel');
2529 } else {
2530 $buttonarray=array();
2531 $buttonarray[] = &$mform->createElement('submit', 'submitbutton', get_string('savechanges'));
2532 $buttonarray[] = &$mform->createElement('cancel');
2533 }
2534 $mform->addGroup($buttonarray, 'grading_buttonar', '', array(' '), false);
291ee134 2535 $mform->closeHeaderBefore('grading_buttonar');
d2b6ee29 2536 $mform->setType('grading_buttonar', PARAM_RAW);
2537 }
2538
2539 function add_submission_content() {
2540 $mform =& $this->_form;
2541 $mform->addElement('header', 'Submission', get_string('submission', 'assignment'));
2542 $mform->addElement('static', '', '' , $this->_customdata->submission_content );
2543 }
96f4a64b 2544
d2b6ee29 2545 protected function get_editor_options() {
2546 $editoroptions = array();
64f93798
PS
2547 $editoroptions['component'] = 'mod_assignment';
2548 $editoroptions['filearea'] = 'feedback';
d2b6ee29 2549 $editoroptions['noclean'] = false;
64f93798 2550 $editoroptions['maxfiles'] = 0; //TODO: no files for now, we need to first implement assignment_feedback area, integration with gradebook, files support in quickgrading, etc. (skodak)
d2b6ee29 2551 $editoroptions['maxbytes'] = $this->_customdata->maxbytes;
e9de1cf4 2552 $editoroptions['context'] = $this->_customdata->context;
d2b6ee29 2553 return $editoroptions;
2554 }
2555
2556 public function set_data($data) {
2557 $editoroptions = $this->get_editor_options();
2558 if (!isset($data->text)) {
2559 $data->text = '';
2560 }
2561 if (!isset($data->format)) {
2562 $data->textformat = FORMAT_HTML;
2563 } else {
2564 $data->textformat = $data->format;
2565 }
2566
2567 if (!empty($this->_customdata->submission->id)) {
2568 $itemid = $this->_customdata->submission->id;
2569 } else {
2570 $itemid = null;
2571 }
2572
291ee134
AB
2573 switch ($this->_customdata->assignment->assignmenttype) {
2574 case 'upload' :
2575 case 'uploadsingle' :
2576 $data = file_prepare_standard_filemanager($data, 'files', $editoroptions, $this->_customdata->context, 'mod_assignment', 'response', $itemid);
2577 break;
2578 default :
2579 break;
2580 }
2581
64f93798 2582 $data = file_prepare_standard_editor($data, 'submissioncomment', $editoroptions, $this->_customdata->context, $editoroptions['component'], $editoroptions['filearea'], $itemid);
d2b6ee29 2583 return parent::set_data($data);
2584 }
2585
2586 public function get_data() {
2587 $data = parent::get_data();
2588
2589 if (!empty($this->_customdata->submission->id)) {
2590 $itemid = $this->_customdata->submission->id;
2591 } else {
64f93798 2592 $itemid = null; //TODO: this is wrong, itemid MUST be known when saving files!! (skodak)
d2b6ee29 2593 }
2594
2595 if ($data) {
2596 $editoroptions = $this->get_editor_options();
291ee134
AB
2597 switch ($this->_customdata->assignment->assignmenttype) {
2598 case 'upload' :
2599 case 'uploadsingle' :
2600 $data = file_postupdate_standard_filemanager($data, 'files', $editoroptions, $this->_customdata->context, 'mod_assignment', 'response', $itemid);
2601 break;
2602 default :
2603 break;
2604 }
64f93798 2605 $data = file_postupdate_standard_editor($data, 'submissioncomment', $editoroptions, $this->_customdata->context, $editoroptions['component'], $editoroptions['filearea'], $itemid);
d2b6ee29 2606 }
18e6298c
MG
2607
2608 if ($this->use_advanced_grading() && !isset($data->advancedgrading)) {
2609 $data->advancedgrading = null;
2610 }
2611
d2b6ee29 2612 return $data;
2613 }
2614}
2615
b0f2597e 2616/// OTHER STANDARD FUNCTIONS ////////////////////////////////////////////////////////
2617
7af1e882 2618/**
2619 * Deletes an assignment instance
2620 *
2621 * This is done by calling the delete_instance() method of the assignment type class
2622 */
b0f2597e 2623function assignment_delete_instance($id){
c18269c7 2624 global $CFG, $DB;
26b90e70 2625
c18269c7 2626 if (! $assignment = $DB->get_record('assignment', array('id'=>$id))) {
b0f2597e 2627 return false;
26b90e70 2628 }
2629
1fc87774 2630 // fall back to base class if plugin missing
2631 $classfile = "$CFG->dirroot/mod/assignment/type/$assignment->assignmenttype/assignment.class.php";
2632 if (file_exists($classfile)) {
2633 require_once($classfile);
2634 $assignmentclass = "assignment_$assignment->assignmenttype";
2635
2636 } else {
2637 debugging("Missing assignment plug-in: {$assignment->assignmenttype}. Using base class for deleting instead.");
2638 $assignmentclass = "assignment_base";
2639 }
2640
b0f2597e 2641 $ass = new $assignmentclass();
2642 return $ass->delete_instance($assignment);
2643}
f466c9ed 2644
ac21ad39 2645
7af1e882 2646/**
2647 * Updates an assignment instance
2648 *
2649 * This is done by calling the update_instance() method of the assignment type class
2650 */
b0f2597e 2651function assignment_update_instance($assignment){
2652 global $CFG;
26b90e70 2653
aff24313 2654 $assignment->assignmenttype = clean_param($assignment->assignmenttype, PARAM_PLUGIN);
200c19fb 2655
b0f2597e 2656 require_once("$CFG->dirroot/mod/assignment/type/$assignment->assignmenttype/assignment.class.php");
2657 $assignmentclass = "assignment_$assignment->assignmenttype";
2658 $ass = new $assignmentclass();
2659 return $ass->update_instance($assignment);
45fa3412 2660}
26b90e70 2661
26b90e70 2662
7af1e882 2663/**
2664 * Adds an assignment instance
2665 *
2666 * This is done by calling the add_instance() method of the assignment type class
2667 */
b0f2597e 2668function assignment_add_instance($assignment) {
2669 global $CFG;
f466c9ed 2670
aff24313 2671 $assignment->assignmenttype = clean_param($assignment->assignmenttype, PARAM_PLUGIN);
200c19fb 2672
b0f2597e 2673 require_once("$CFG->dirroot/mod/assignment/type/$assignment->assignmenttype/assignment.class.php");
2674 $assignmentclass = "assignment_$assignment->assignmenttype";
2675 $ass = new $assignmentclass();
2676 return $ass->add_instance($assignment);
2677}
f466c9ed 2678
73097f07 2679
7af1e882 2680/**
2681 * Returns an outline of a user interaction with an assignment
2682 *
2683 * This is done by calling the user_outline() method of the assignment type class
2684 */
73097f07 2685function assignment_user_outline($course, $user, $mod, $assignment) {
2686 global $CFG;
2687
1a96363a 2688 require_once("$CFG->libdir/gradelib.php");
73097f07 2689 require_once("$CFG->dirroot/mod/assignment/type/$assignment->assignmenttype/assignment.class.php");
2690 $assignmentclass = "assignment_$assignment->assignmenttype";
2691 $ass = new $assignmentclass($mod->id, $assignment, $mod, $course);
1a96363a
NC
2692 $grades = grade_get_grades($course->id, 'mod', 'assignment', $assignment->id, $user->id);
2693 if (!empty($grades->items[0]->grades)) {
2694 return $ass->user_outline(reset($grades->items[0]->grades));
2695 } else {
2696 return null;
2697 }
73097f07 2698}
2699
7af1e882 2700/**
2701 * Prints the complete info about a user's interaction with an assignment
2702 *
2703 * This is done by calling the user_complete() method of the assignment type class
2704 */
73097f07 2705function assignment_user_complete($course, $user, $mod, $assignment) {
2706 global $CFG;
2707
1a96363a 2708 require_once("$CFG->libdir/gradelib.php");
73097f07 2709 require_once("$CFG->dirroot/mod/assignment/type/$assignment->assignmenttype/assignment.class.php");
2710 $assignmentclass = "assignment_$assignment->assignmenttype";
2711 $ass = new $assignmentclass($mod->id, $assignment, $mod, $course);
1a96363a
NC
2712 $grades = grade_get_grades($course->id, 'mod', 'assignment', $assignment->id, $user->id);
2713 if (empty($grades->items[0]->grades)) {
2714 $grade = false;
2715 } else {
2716 $grade = reset($grades->items[0]->grades);
2717 }
2718 return $ass->user_complete($user, $grade);
73097f07 2719}
2720
7af1e882 2721/**
2722 * Function to be run periodically according to the moodle cron
2723 *
2724 * Finds all assignment notifications that have yet to be mailed out, and mails them
2725 */
73097f07 2726function assignment_cron () {
5053f00f 2727 global $CFG, $USER, $DB;
73097f07 2728
d014b69b 2729 /// first execute all crons in plugins
17da2e6f 2730 if ($plugins = get_plugin_list('assignment')) {
2731 foreach ($plugins as $plugin=>$dir) {
2732 require_once("$dir/assignment.class.php");
d014b69b 2733 $assignmentclass = "assignment_$plugin";
2734 $ass = new $assignmentclass();
2735 $ass->cron();
2736 }
2737 }
2738
73097f07 2739 /// Notices older than 1 day will not be mailed. This is to avoid the problem where
2740 /// cron has not been running for a long time, and then suddenly people are flooded
2741 /// with mail from the past few weeks or months
2742
2743 $timenow = time();
2744 $endtime = $timenow - $CFG->maxeditingtime;
2745 $starttime = $endtime - 24 * 3600; /// One day earlier
2746
2747 if ($submissions = assignment_get_unmailed_submissions($starttime, $endtime)) {
2748
98be6ed8 2749 $realuser = clone($USER);
2750
73097f07 2751 foreach ($submissions as $key => $submission) {
f685e830 2752 $DB->set_field("assignment_submissions", "mailed", "1", array("id"=>$submission->id));
73097f07 2753 }
2754
2755 $timenow = time();
2756
2757 foreach ($submissions as $submission) {
2758
2759 echo "Processing assignment submission $submission->id\n";
2760
5053f00f 2761 if (! $user = $DB->get_record("user", array("id"=>$submission->userid))) {
6b1564a8 2762 echo "Could not find user $user->id\n";
73097f07 2763 continue;
2764 }
2765
5053f00f 2766 if (! $course = $DB->get_record("course", array("id"=>$submission->course))) {
73097f07 2767 echo "Could not find course $submission->course\n";
2768 continue;
2769 }
98be6ed8 2770
2771 /// Override the language and timezone of the "current" user, so that
2772 /// mail is customised for the receiver.
e8b7114d 2773 cron_setup_user($user, $course);
98be6ed8 2774
8ebbb06a
SH
2775 $coursecontext = get_context_instance(CONTEXT_COURSE, $submission->course);
2776 $courseshortname = format_string($course->shortname, true, array('context' => $coursecontext));
2777 if (!is_enrolled($coursecontext, $user->id)) {
2778 echo fullname($user)." not an active participant in " . $courseshortname . "\n";
73097f07 2779 continue;
2780 }
2781
5053f00f 2782 if (! $teacher = $DB->get_record("user", array("id"=>$submission->teacher))) {
73097f07 2783 echo "Could not find teacher $submission->teacher\n";
2784 continue;
2785 }
2786
2787 if (! $mod = get_coursemodule_from_instance("assignment", $submission->assignment, $course->id)) {
2788 echo "Could not find course module for assignment id $submission->assignment\n";
2789 continue;
2790 }
2791
2792 if (! $mod->visible) { /// Hold mail notification for hidden assignments until later
2793 continue;
2794 }
2795
2796 $strassignments = get_string("modulenameplural", "assignment");
2797 $strassignment = get_string("modulename", "assignment");
2798
39790bd8 2799 $assignmentinfo = new stdClass();
73097f07 2800 $assignmentinfo->teacher = fullname($teacher);
2801 $assignmentinfo->assignment = format_string($submission->name,true);
2802 $assignmentinfo->url = "$CFG->wwwroot/mod/assignment/view.php?id=$mod->id";
2803
8ebbb06a
SH
2804 $postsubject = "$courseshortname: $strassignments: ".format_string($submission->name,true);
2805 $posttext = "$courseshortname -> $strassignments -> ".format_string($submission->name,true)."\n";
73097f07 2806 $posttext .= "---------------------------------------------------------------------\n";
3f19bff3 2807 $posttext .= get_string("assignmentmail", "assignment", $assignmentinfo)."\n";
73097f07 2808 $posttext .= "---------------------------------------------------------------------\n";
2809
2810 if ($user->mailformat == 1) { // HTML
2811 $posthtml = "<p><font face=\"sans-serif\">".
8ebbb06a 2812 "<a href=\"$CFG->wwwroot/course/view.php?id=$course->id\">$courseshortname</a> ->".
73097f07 2813 "<a href=\"$CFG->wwwroot/mod/assignment/index.php?id=$course->id\">$strassignments</a> ->".
2814 "<a href=\"$CFG->wwwroot/mod/assignment/view.php?id=$mod->id\">".format_string($submission->name,true)."</a></font></p>";
2815 $posthtml .= "<hr /><font face=\"sans-serif\">";
2816 $posthtml .= "<p>".get_string("assignmentmailhtml", "assignment", $assignmentinfo)."</p>";
2817 $posthtml .= "</font><hr />";
2818 } else {
2819 $posthtml = "";
2820 }
2821
39790bd8 2822 $eventdata = new stdClass();
3b120e46 2823 $eventdata->modulename = 'assignment';
2824 $eventdata->userfrom = $teacher;
2825 $eventdata->userto = $user;
2826 $eventdata->subject = $postsubject;
2827 $eventdata->fullmessage = $posttext;
2828 $eventdata->fullmessageformat = FORMAT_PLAIN;
2829 $eventdata->fullmessagehtml = $posthtml;
5daa7279 2830 $eventdata->smallmessage = get_string('assignmentmailsmall', 'assignment', $assignmentinfo);
d042ff06
AB
2831
2832 $eventdata->name = 'assignment_updates';
2833 $eventdata->component = 'mod_assignment';
2834 $eventdata->notification = 1;
0f1751b0
AD
2835 $eventdata->contexturl = $assignmentinfo->url;
2836 $eventdata->contexturlname = $assignmentinfo->assignment;
d042ff06 2837
7c7d3afa 2838 message_send($eventdata);
73097f07 2839 }
98be6ed8 2840
e8b7114d 2841 cron_setup_user();
73097f07 2842 }
2843
2844 return true;
2845}
2846
45fa3412 2847/**
2848 * Return grade for given user or all users.
2849 *
2850 * @param int $assignmentid id of assignment
2851 * @param int $userid optional user id, 0 means all users
2852 * @return array array of grades, false if none
2853 */
612607bd 2854function assignment_get_user_grades($assignment, $userid=0) {
5053f00f 2855 global $CFG, $DB;
45fa3412 2856
5053f00f 2857 if ($userid) {
2858 $user = "AND u.id = :userid";
2859 $params = array('userid'=>$userid);
2860 } else {
2861 $user = "";
2862 }
2863 $params['aid'] = $assignment->id;
45fa3412 2864
ced5ee59 2865 $sql = "SELECT u.id, u.id AS userid, s.grade AS rawgrade, s.submissioncomment AS feedback, s.format AS feedbackformat,
2866 s.teacher AS usermodified, s.timemarked AS dategraded, s.timemodified AS datesubmitted
5053f00f 2867 FROM {user} u, {assignment_submissions} s
2868 WHERE u.id = s.userid AND s.assignment = :aid
4a1be95c 2869 $user";
45fa3412 2870
5053f00f 2871 return $DB->get_records_sql($sql, $params);
45fa3412 2872}
2873
2874/**
775f811a 2875 * Update activity grades
45fa3412 2876 *
775f811a 2877 * @param object $assignment
2878 * @param int $userid specific user only, 0 means all
45fa3412 2879 */
775f811a 2880function assignment_update_grades($assignment, $userid=0, $nullifnone=true) {
5053f00f 2881 global $CFG, $DB;
2882 require_once($CFG->libdir.'/gradelib.php');
45fa3412 2883
775f811a 2884 if ($assignment->grade == 0) {
2885 assignment_grade_item_update($assignment);
2886
2887 } else if ($grades = assignment_get_user_grades($assignment, $userid)) {
2888 foreach($grades as $k=>$v) {
2889 if ($v->rawgrade == -1) {
2890 $grades[$k]->rawgrade = null;
45fa3412 2891 }
2892 }
775f811a 2893 assignment_grade_item_update($assignment, $grades);
45fa3412 2894
2895 } else {
775f811a 2896 assignment_grade_item_update($assignment);
2897 }
2898}
2899
2900/**
2901 * Update all grades in gradebook.
2902 */
2903function assignment_upgrade_grades() {
2904 global $DB;
2905
2906 $sql = "SELECT COUNT('x')
2907 FROM {assignment} a, {course_modules} cm, {modules} m
2908 WHERE m.name='assignment' AND m.id=cm.module AND cm.instance=a.id";
2909 $count = $DB->count_records_sql($sql);
2910
2911 $sql = "SELECT a.*, cm.idnumber AS cmidnumber, a.course AS courseid
2912 FROM {assignment} a, {course_modules} cm, {modules} m
2913 WHERE m.name='assignment' AND m.id=cm.module AND cm.instance=a.id";
6b1b1d03
EL
2914 $rs = $DB->get_recordset_sql($sql);
2915 if ($rs->valid()) {
775f811a 2916 // too much debug output
775f811a 2917 $pbar = new progress_bar('assignmentupgradegrades', 500, true);
2918 $i=0;
2919 foreach ($rs as $assignment) {
2920 $i++;
2921 upgrade_set_timeout(60*5); // set up timeout, may also abort execution
2922 assignment_update_grades($assignment);
2923 $pbar->update($i, $count, "Updating Assignment grades ($i/$count).");
2924 }
775f811a 2925 upgrade_set_timeout(); // reset to default timeout
45fa3412 2926 }
6b1b1d03 2927 $rs->close();
45fa3412 2928}
2929
2930/**
612607bd 2931 * Create grade item for given assignment
45fa3412 2932 *
8b4fb44e 2933 * @param object $assignment object with extra cmidnumber
0b5a80a1 2934 * @param mixed optional array/object of grade(s); 'reset' means reset grades in gradebook
612607bd 2935 * @return int 0 if ok, error code otherwise
45fa3412 2936 */
ced5ee59 2937function assignment_grade_item_update($assignment, $grades=NULL) {
612607bd 2938 global $CFG;
5053f00f 2939 require_once($CFG->libdir.'/gradelib.php');
45fa3412 2940
8b4fb44e 2941 if (!isset($assignment->courseid)) {
2942 $assignment->courseid = $assignment->course;
2943 }
2944
612607bd 2945 $params = array('itemname'=>$assignment->name, 'idnumber'=>$assignment->cmidnumber);
45fa3412 2946
2947 if ($assignment->grade > 0) {
2948 $params['gradetype'] = GRADE_TYPE_VALUE;
2949 $params['grademax'] = $assignment->grade;
2950 $params['grademin'] = 0;
2951
2952 } else if ($assignment->grade < 0) {
2953 $params['gradetype'] = GRADE_TYPE_SCALE;
2954 $params['scaleid'] = -$assignment->grade;
2955
2956 } else {
5048575d 2957 $params['gradetype'] = GRADE_TYPE_TEXT; // allow text comments only
45fa3412 2958 }
2959
0b5a80a1 2960 if ($grades === 'reset') {
2961 $params['reset'] = true;
2962 $grades = NULL;
2963 }
2964
ced5ee59 2965 return grade_update('mod/assignment', $assignment->courseid, 'mod', 'assignment', $assignment->id, 0, $grades, $params);
45fa3412 2966}
2967
2968/**
2969 * Delete grade item for given assignment
2970 *
8b4fb44e 2971 * @param object $assignment object
612607bd 2972 * @return object assignment
45fa3412 2973 */
2974function assignment_grade_item_delete($assignment) {
612607bd 2975 global $CFG;
2976 require_once($CFG->libdir.'/gradelib.php');
2977
8b4fb44e 2978 if (!isset($assignment->courseid)) {
2979 $assignment->courseid = $assignment->course;
2980 }
2981
b67ec72f 2982 return grade_update('mod/assignment', $assignment->courseid, 'mod', 'assignment', $assignment->id, 0, NULL, array('deleted'=>1));
45fa3412 2983}
2984
7af1e882 2985/**
2986 * Returns the users with data in one assignment (students and teachers)
2987 *
2b04c41c
SH
2988 * @todo: deprecated - to be deleted in 2.2
2989 *
7af1e882 2990 * @param $assignmentid int
2991 * @return array of user objects
2992 */
73097f07 2993function assignment_get_participants($assignmentid) {
5053f00f 2994 global $CFG, $DB;
73097f07 2995
2996 //Get students
5053f00f 2997 $students = $DB->get_records_sql("SELECT DISTINCT u.id, u.id
2998 FROM {user} u,
2999 {assignment_submissions} a
3000 WHERE a.assignment = ? and
3001 u.id = a.userid", array($assignmentid));
73097f07 3002 //Get teachers
5053f00f 3003 $teachers = $DB->get_records_sql("SELECT DISTINCT u.id, u.id
3004 FROM {user} u,
3005 {assignment_submissions} a
3006 WHERE a.assignment = ? and
3007 u.id = a.teacher", array($assignmentid));
73097f07