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