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