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