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