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