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