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