MDL-33791 Portfolio: Fixed security issue with passing file paths.
[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');
1400
b0f2597e 1401 // Start working -- this is necessary as soon as the niceties are over
1402 $table->setup();
1403
54c37fbd 1404 /// Construct the SQL
0f21a964
PS
1405 list($where, $params) = $table->get_sql_where();
1406 if ($where) {
b0f2597e 1407 $where .= ' AND ';
1408 }
de75c481 1409
0f21a964 1410 if ($filter == self::FILTER_SUBMITTED) {
de75c481 1411 $where .= 's.timemodified > 0 AND ';
fdb797ad 1412 } else if($filter == self::FILTER_REQUIRE_GRADING) {
54c37fbd
RW
1413 $where = '';
1414 if ($assignment->assignmenttype != 'offline') {
1415 $where .= 's.timemarked < s.timemodified AND ';
1416 }
fdb797ad 1417 }
0f1a97c2 1418
b0f2597e 1419 if ($sort = $table->get_sql_sort()) {
86f65395 1420 $sort = ' ORDER BY '.$sort;
b0f2597e 1421 }
9fa49e22 1422
02dd3b9f 1423 $ufields = user_picture::fields('u', $extrafields);
e512715b
RW
1424 if (!empty($users)) {
1425 $select = "SELECT $ufields,
1426 s.id AS submissionid, s.grade, s.submissioncomment,
8c93ab4e
SB
1427 s.timemodified, s.timemarked,
1428 CASE WHEN s.timemarked > 0 AND s.timemarked >= s.timemodified THEN 1
1429 ELSE 0 END AS status ";
1430
e512715b
RW
1431 $sql = 'FROM {user} u '.
1432 'LEFT JOIN {assignment_submissions} s ON u.id = s.userid
1433 AND s.assignment = '.$this->assignment->id.' '.
1434 'WHERE '.$where.'u.id IN ('.implode(',',$users).') ';
1435
1436 $ausers = $DB->get_records_sql($select.$sql.$sort, $params, $table->get_page_start(), $table->get_page_size());
1437
1438 $table->pagesize($perpage, count($users));
1439
1440 ///offset used to calculate index of student in that particular query, needed for the pop up to know who's next
1441 $offset = $page * $perpage;
1442 $strupdate = get_string('update');
1443 $strgrade = get_string('grade');
7761e7b3 1444 $strview = get_string('view');
e512715b
RW
1445 $grademenu = make_grades_menu($this->assignment->grade);
1446
1447 if ($ausers !== false) {
1448 $grading_info = grade_get_grades($this->course->id, 'mod', 'assignment', $this->assignment->id, array_keys($ausers));
1449 $endposition = $offset + $perpage;
1450 $currentposition = 0;
1451 foreach ($ausers as $auser) {
1452 if ($currentposition == $offset && $offset < $endposition) {
d50645eb 1453 $rowclass = null;
e512715b
RW
1454 $final_grade = $grading_info->items[0]->grades[$auser->id];
1455 $grademax = $grading_info->items[0]->grademax;
1456 $final_grade->formatted_grade = round($final_grade->grade,2) .' / ' . round($grademax,2);
1457 $locked_overridden = 'locked';
1458 if ($final_grade->overridden) {
1459 $locked_overridden = 'overridden';
1460 }
fdb797ad 1461
9e2eca0f 1462 // TODO add here code if advanced grading grade must be reviewed => $auser->status=0
1ae9aa2b 1463
e512715b 1464 $picture = $OUTPUT->user_picture($auser);
45fa3412 1465
e512715b
RW
1466 if (empty($auser->submissionid)) {
1467 $auser->grade = -1; //no submission yet
1468 }
45fa3412 1469
e512715b
RW
1470 if (!empty($auser->submissionid)) {
1471 $hassubmission = true;
1472 ///Prints student answer and student modified date
1473 ///attach file or print link to student answer, depending on the type of the assignment.
1474 ///Refer to print_student_answer in inherited classes.
1475 if ($auser->timemodified > 0) {
d50645eb
ARN
1476 $studentmodifiedcontent = $this->print_student_answer($auser->id)
1477 . userdate($auser->timemodified);
2159c1ea
HB
1478 if ($assignment->timedue && $auser->timemodified > $assignment->timedue && $this->supports_lateness()) {
1479 $studentmodifiedcontent .= $this->display_lateness($auser->timemodified);
d50645eb
ARN
1480 $rowclass = 'late';
1481 }
e512715b 1482 } else {
d50645eb 1483 $studentmodifiedcontent = '&nbsp;';
e512715b 1484 }
d50645eb 1485 $studentmodified = html_writer::tag('div', $studentmodifiedcontent, array('id' => 'ts' . $auser->id));
e512715b
RW
1486 ///Print grade, dropdown or text
1487 if ($auser->timemarked > 0) {
1488 $teachermodified = '<div id="tt'.$auser->id.'">'.userdate($auser->timemarked).'</div>';
1489
1490 if ($final_grade->locked or $final_grade->overridden) {
1491 $grade = '<div id="g'.$auser->id.'" class="'. $locked_overridden .'">'.$final_grade->formatted_grade.'</div>';
1492 } else if ($quickgrade) {
1493 $attributes = array();
1494 $attributes['tabindex'] = $tabindex++;
5d2b1e5e 1495 $menu = html_writer::label(get_string('assignment:grade', 'assignment'), 'menumenu'. $auser->id, false, array('class' => 'accesshide'));
3695494f 1496 $menu .= html_writer::select(make_grades_menu($this->assignment->grade), 'menu['.$auser->id.']', $auser->grade, array(-1=>get_string('nograde')), $attributes);
e512715b
RW
1497 $grade = '<div id="g'.$auser->id.'">'. $menu .'</div>';
1498 } else {
1499 $grade = '<div id="g'.$auser->id.'">'.$this->display_grade($auser->grade).'</div>';
1500 }
45fa3412 1501
e512715b
RW
1502 } else {
1503 $teachermodified = '<div id="tt'.$auser->id.'">&nbsp;</div>';
1504 if ($final_grade->locked or $final_grade->overridden) {
1505 $grade = '<div id="g'.$auser->id.'" class="'. $locked_overridden .'">'.$final_grade->formatted_grade.'</div>';
1506 } else if ($quickgrade) {
1507 $attributes = array();
1508 $attributes['tabindex'] = $tabindex++;
3695494f
RW
1509 $menu = html_writer::label(get_string('assignment:grade', 'assignment'), 'menumenu'. $auser->id, false, array('class' => 'accesshide'));
1510 $menu .= html_writer::select(make_grades_menu($this->assignment->grade), 'menu['.$auser->id.']', $auser->grade, array(-1=>get_string('nograde')), $attributes);
e512715b
RW
1511 $grade = '<div id="g'.$auser->id.'">'.$menu.'</div>';
1512 } else {
1513 $grade = '<div id="g'.$auser->id.'">'.$this->display_grade($auser->grade).'</div>';
1514 }
1515 }
1516 ///Print Comment
1517 if ($final_grade->locked or $final_grade->overridden) {
1518 $comment = '<div id="com'.$auser->id.'">'.shorten_text(strip_tags($final_grade->str_feedback),15).'</div>';
1519
1520 } else if ($quickgrade) {
1521 $comment = '<div id="com'.$auser->id.'">'
1522 . '<textarea tabindex="'.$tabindex++.'" name="submissioncomment['.$auser->id.']" id="submissioncomment'
1523 . $auser->id.'" rows="2" cols="20">'.($auser->submissioncomment).'</textarea></div>';
1524 } else {
1525 $comment = '<div id="com'.$auser->id.'">'.shorten_text(strip_tags($auser->submissioncomment),15).'</div>';
1526 }
fdb797ad
RW
1527 } else {
1528 $studentmodified = '<div id="ts'.$auser->id.'">&nbsp;</div>';
e512715b
RW
1529 $teachermodified = '<div id="tt'.$auser->id.'">&nbsp;</div>';
1530 $status = '<div id="st'.$auser->id.'">&nbsp;</div>';
fdb797ad
RW
1531
1532 if ($final_grade->locked or $final_grade->overridden) {
e512715b
RW
1533 $grade = '<div id="g'.$auser->id.'">'.$final_grade->formatted_grade . '</div>';
1534 $hassubmission = true;
1535 } else if ($quickgrade) { // allow editing
fdb797ad
RW
1536 $attributes = array();
1537 $attributes['tabindex'] = $tabindex++;
3695494f
RW
1538 $menu = html_writer::label(get_string('assignment:grade', 'assignment'), 'menumenu'. $auser->id, false, array('class' => 'accesshide'));
1539 $menu .= html_writer::select(make_grades_menu($this->assignment->grade), 'menu['.$auser->id.']', $auser->grade, array(-1=>get_string('nograde')), $attributes);
e512715b
RW
1540 $grade = '<div id="g'.$auser->id.'">'.$menu.'</div>';
1541 $hassubmission = true;
fdb797ad 1542 } else {
e512715b 1543 $grade = '<div id="g'.$auser->id.'">-</div>';
fdb797ad
RW
1544 }
1545
fdb797ad 1546 if ($final_grade->locked or $final_grade->overridden) {
e512715b 1547 $comment = '<div id="com'.$auser->id.'">'.$final_grade->str_feedback.'</div>';
fdb797ad 1548 } else if ($quickgrade) {
e512715b
RW
1549 $comment = '<div id="com'.$auser->id.'">'
1550 . '<textarea tabindex="'.$tabindex++.'" name="submissioncomment['.$auser->id.']" id="submissioncomment'
1551 . $auser->id.'" rows="2" cols="20">'.($auser->submissioncomment).'</textarea></div>';
fdb797ad 1552 } else {
e512715b 1553 $comment = '<div id="com'.$auser->id.'">&nbsp;</div>';
fdb797ad
RW
1554 }
1555 }
fdb797ad 1556
e512715b
RW
1557 if (empty($auser->status)) { /// Confirm we have exclusively 0 or 1
1558 $auser->status = 0;
fdb797ad 1559 } else {
e512715b 1560 $auser->status = 1;
9bf660b3 1561 }
206ab184 1562
e512715b 1563 $buttontext = ($auser->status == 1) ? $strupdate : $strgrade;
7761e7b3
RK
1564 if ($final_grade->locked or $final_grade->overridden) {
1565 $buttontext = $strview;
1566 }
0f7d4e5e 1567
e512715b
RW
1568 ///No more buttons, we use popups ;-).
1569 $popup_url = '/mod/assignment/submissions.php?id='.$this->cm->id
1570 . '&amp;userid='.$auser->id.'&amp;mode=single'.'&amp;filter='.$filter.'&amp;offset='.$offset++;
45fa3412 1571
e512715b 1572 $button = $OUTPUT->action_link($popup_url, $buttontext);
a9573c08 1573
e512715b 1574 $status = '<div id="up'.$auser->id.'" class="s'.$auser->status.'">'.$button.'</div>';
206ab184 1575
e512715b 1576 $finalgrade = '<span id="finalgrade_'.$auser->id.'">'.$final_grade->str_grade.'</span>';
cc03871b 1577
e512715b 1578 $outcomes = '';
5978010d 1579
e512715b 1580 if ($uses_outcomes) {
206ab184 1581
e512715b 1582 foreach($grading_info->outcomes as $n=>$outcome) {
3695494f 1583 $outcomes .= '<div class="outcome"><label for="'. 'outcome_'.$n.'_'.$auser->id .'">'.$outcome->name.'</label>';
e512715b 1584 $options = make_grades_menu(-$outcome->scaleid);
206ab184 1585
e512715b
RW
1586 if ($outcome->grades[$auser->id]->locked or !$quickgrade) {
1587 $options[0] = get_string('nooutcome', 'grades');
1588 $outcomes .= ': <span id="outcome_'.$n.'_'.$auser->id.'">'.$options[$outcome->grades[$auser->id]->grade].'</span>';
1589 } else {
1590 $attributes = array();
1591 $attributes['tabindex'] = $tabindex++;
1592 $attributes['id'] = 'outcome_'.$n.'_'.$auser->id;
1593 $outcomes .= ' '.html_writer::select($options, 'outcome_'.$n.'['.$auser->id.']', $outcome->grades[$auser->id]->grade, array(0=>get_string('nooutcome', 'grades')), $attributes);
1594 }
1595 $outcomes .= '</div>';
fdb797ad 1596 }
cc03871b 1597 }
cc03871b 1598
e512715b 1599 $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 1600 $extradata = array();
1601 foreach ($extrafields as $field) {
1602 $extradata[] = $auser->{$field};
1603 }
1604 $row = array_merge(array($picture, $userlink), $extradata,
1605 array($grade, $comment, $studentmodified, $teachermodified,
1606 $status, $finalgrade));
e512715b
RW
1607 if ($uses_outcomes) {
1608 $row[] = $outcomes;
1609 }
d50645eb 1610 $table->add_data($row, $rowclass);
fdb797ad 1611 }
e512715b 1612 $currentposition++;
fdb797ad 1613 }
0652b34f 1614 if ($hassubmission && method_exists($this, 'download_submissions')) {
54c37fbd
RW
1615 echo html_writer::start_tag('div', array('class' => 'mod-assignment-download-link'));
1616 echo html_writer::link(new moodle_url('/mod/assignment/submissions.php', array('id' => $this->cm->id, 'download' => 'zip')), get_string('downloadall', 'assignment'));
1617 echo html_writer::end_tag('div');
1618 }
1619 $table->print_html(); /// Print the whole table
1620 } else {
1621 if ($filter == self::FILTER_SUBMITTED) {
1622 echo html_writer::tag('div', get_string('nosubmisson', 'assignment'), array('class'=>'nosubmisson'));
1623 } else if ($filter == self::FILTER_REQUIRE_GRADING) {
1624 echo html_writer::tag('div', get_string('norequiregrading', 'assignment'), array('class'=>'norequiregrading'));
1625 }
d59269cf 1626 }
b0f2597e 1627 }
45fa3412 1628
fdb797ad 1629 /// Print quickgrade form around the table
e512715b 1630 if ($quickgrade && $table->started_output && !empty($users)){
fdb797ad
RW
1631 $mailinfopref = false;
1632 if (get_user_preferences('assignment_mailinfo', 1)) {
1633 $mailinfopref = true;
1634 }
be34802d 1635 $emailnotification = html_writer::checkbox('mailinfo', 1, $mailinfopref, get_string('enablenotification','assignment'));
de75c481 1636
be34802d 1637 $emailnotification .= $OUTPUT->help_icon('enablenotification', 'assignment');
fdb797ad
RW
1638 echo html_writer::tag('div', $emailnotification, array('class'=>'emailnotification'));
1639
1640 $savefeedback = html_writer::empty_tag('input', array('type'=>'submit', 'name'=>'fastg', 'value'=>get_string('saveallfeedback', 'assignment')));
1641 echo html_writer::tag('div', $savefeedback, array('class'=>'fastgbutton'));
de75c481
RW
1642
1643 echo html_writer::end_tag('form');
fdb797ad 1644 } else if ($quickgrade) {
de75c481 1645 echo html_writer::end_tag('form');
9bf660b3 1646 }
fdb797ad
RW
1647
1648 echo '</div>';
082215e6 1649 /// End of fast grading form
45fa3412 1650
de75c481
RW
1651 /// Mini form for setting user preference
1652
fdb797ad
RW
1653 $formaction = new moodle_url('/mod/assignment/submissions.php', array('id'=>$this->cm->id));
1654 $mform = new MoodleQuickForm('optionspref', 'post', $formaction, '', array('class'=>'optionspref'));
de75c481 1655
fdb797ad
RW
1656 $mform->addElement('hidden', 'updatepref');
1657 $mform->setDefault('updatepref', 1);
1658 $mform->addElement('header', 'qgprefs', get_string('optionalsettings', 'assignment'));
1659 $mform->addElement('select', 'filter', get_string('show'), $filters);
de75c481 1660
fdb797ad
RW
1661 $mform->setDefault('filter', $filter);
1662
1663 $mform->addElement('text', 'perpage', get_string('pagesize', 'assignment'), array('size'=>1));
de75c481 1664 $mform->setDefault('perpage', $perpage);
fdb797ad 1665
9e2eca0f
MG
1666 if ($this->quickgrade_mode_allowed()) {
1667 $mform->addElement('checkbox', 'quickgrade', get_string('quickgrade','assignment'));
1668 $mform->setDefault('quickgrade', $quickgrade);
1669 $mform->addHelpButton('quickgrade', 'quickgrade', 'assignment');
1670 }
de75c481 1671
fdb797ad
RW
1672 $mform->addElement('submit', 'savepreferences', get_string('savepreferences'));
1673
1674 $mform->display();
de75c481 1675
256d2850 1676 echo $OUTPUT->footer();
8e340cb0 1677 }
d699cd1e 1678
18e6298c 1679 /**
36937f02
MG
1680 * If the form was cancelled ('Cancel' or 'Next' was pressed), call cancel method
1681 * from advanced grading (if applicable) and returns true
1682 * If the form was submitted, validates it and returns false if validation did not pass.
18e6298c 1683 * If validation passes, preprocess advanced grading (if applicable) and returns true.
3c2b3cb3
MG
1684 *
1685 * Note to the developers: This is NOT the correct way to implement advanced grading
1686 * in grading form. The assignment grading was written long time ago and unfortunately
1687 * does not fully use the mforms. Usually function is_validated() is called to
1688 * validate the form and get_data() is called to get the data from the form.
1689 *
1690 * Here we have to push the calculated grade to $_POST['xgrade'] because further processing
1691 * of the form gets the data not from form->get_data(), but from $_POST (using statement
1692 * like $feedback = data_submitted() )
18e6298c 1693 */
3c2b3cb3 1694 protected function validate_and_preprocess_feedback() {
71380f2f
MG
1695 global $USER, $CFG;
1696 require_once($CFG->libdir.'/gradelib.php');
36937f02 1697 if (!($feedback = data_submitted()) || !isset($feedback->userid) || !isset($feedback->offset)) {
18e6298c
MG
1698 return true; // No incoming data, nothing to validate
1699 }
1700 $userid = required_param('userid', PARAM_INT);
1701 $offset = required_param('offset', PARAM_INT);
3c2b3cb3
MG
1702 $gradinginfo = grade_get_grades($this->course->id, 'mod', 'assignment', $this->assignment->id, array($userid));
1703 $gradingdisabled = $gradinginfo->items[0]->grades[$userid]->locked || $gradinginfo->items[0]->grades[$userid]->overridden;
71380f2f
MG
1704 if ($gradingdisabled) {
1705 return true;
1706 }
18e6298c
MG
1707 $submissiondata = $this->display_submission($offset, $userid, false);
1708 $mform = $submissiondata->mform;
36937f02
MG
1709 $gradinginstance = $mform->use_advanced_grading();
1710 if (optional_param('cancel', false, PARAM_BOOL) || optional_param('next', false, PARAM_BOOL)) {
1711 // form was cancelled
1712 if ($gradinginstance) {
1713 $gradinginstance->cancel();
1714 }
1715 } else if ($mform->is_submitted()) {
1716 // form was submitted (= a submit button other than 'cancel' or 'next' has been clicked)
18e6298c
MG
1717 if (!$mform->is_validated()) {
1718 return false;
1719 }
1720 // preprocess advanced grading here
36937f02 1721 if ($gradinginstance) {
18e6298c 1722 $data = $mform->get_data();
fc05f222
MG
1723 // create submission if it did not exist yet because we need submission->id for storing the grading instance
1724 $submission = $this->get_submission($userid, true);
1725 $_POST['xgrade'] = $gradinginstance->submit_and_get_grade($data->advancedgrading, $submission->id);
18e6298c
MG
1726 }
1727 }
1728 return true;
1729 }
1730
7af1e882 1731 /**
1732 * Process teacher feedback submission
1733 *
1734 * This is called by submissions() when a grading even has taken place.
1735 * It gets its data from the submitted form.
256578f6 1736 *
1737 * @global object
1738 * @global object
1739 * @global object
1740 * @return object|bool The updated submission object or false
b0f2597e 1741 */
291ee134 1742 function process_feedback($formdata=null) {
f8c81c01 1743 global $CFG, $USER, $DB;
5978010d 1744 require_once($CFG->libdir.'/gradelib.php');
d699cd1e 1745
a19dffc0 1746 if (!$feedback = data_submitted() or !confirm_sesskey()) { // No incoming data?
b0f2597e 1747 return false;
d699cd1e 1748 }
b7b42874 1749
9bf660b3 1750 ///For save and next, we need to know the userid to save, and the userid to go
1751 ///We use a new hidden field in the form, and set it to -1. If it's set, we use this
1752 ///as the userid to store
1753 if ((int)$feedback->saveuserid !== -1){
1754 $feedback->userid = $feedback->saveuserid;
1755 }
1756
b0f2597e 1757 if (!empty($feedback->cancel)) { // User hit cancel button
1758 return false;
1759 }
d699cd1e 1760
5978010d 1761 $grading_info = grade_get_grades($this->course->id, 'mod', 'assignment', $this->assignment->id, $feedback->userid);
1762
cc03871b 1763 // store outcomes if needed
1764 $this->process_outcomes($feedback->userid);
1765
7af1e882 1766 $submission = $this->get_submission($feedback->userid, true); // Get or make one
d699cd1e 1767
d2b6ee29 1768 if (!($grading_info->items[0]->grades[$feedback->userid]->locked ||
1769 $grading_info->items[0]->grades[$feedback->userid]->overridden) ) {
d699cd1e 1770
d2b6ee29 1771 $submission->grade = $feedback->xgrade;
1772 $submission->submissioncomment = $feedback->submissioncomment_editor['text'];
5978010d 1773 $submission->teacher = $USER->id;
2dc5d980 1774 $mailinfo = get_user_preferences('assignment_mailinfo', 0);
1775 if (!$mailinfo) {
1776 $submission->mailed = 1; // treat as already mailed
1777 } else {
1778 $submission->mailed = 0; // Make sure mail goes out (again, even)
1779 }
5978010d 1780 $submission->timemarked = time();
d4156e80 1781
5978010d 1782 unset($submission->data1); // Don't need to update this.
1783 unset($submission->data2); // Don't need to update this.
d699cd1e 1784
5978010d 1785 if (empty($submission->timemodified)) { // eg for offline assignments
1786 // $submission->timemodified = time();
1787 }
d699cd1e 1788
0bcf8b6f 1789 $DB->update_record('assignment_submissions', $submission);
7bddd4b7 1790
5978010d 1791 // triger grade event
1792 $this->update_grade($submission);
1793
1794 add_to_log($this->course->id, 'assignment', 'update grades',
0f66aced 1795 'submissions.php?id='.$this->cm->id.'&user='.$feedback->userid, $feedback->userid, $this->cm->id);
291ee134
AB
1796 if (!is_null($formdata)) {
1797 if ($this->type == 'upload' || $this->type == 'uploadsingle') {
1798 $mformdata = $formdata->mform->get_data();
1799 $mformdata = file_postupdate_standard_filemanager($mformdata, 'files', $formdata->fileui_options, $this->context, 'mod_assignment', 'response', $submission->id);
1800 }
1801 }
5978010d 1802 }
45fa3412 1803
7af1e882 1804 return $submission;
d699cd1e 1805
d699cd1e 1806 }
d699cd1e 1807
cc03871b 1808 function process_outcomes($userid) {
1809 global $CFG, $USER;
fbaa56b2 1810
1811 if (empty($CFG->enableoutcomes)) {
1812 return;
1813 }
1814
cc03871b 1815 require_once($CFG->libdir.'/gradelib.php');
1816
a19dffc0 1817 if (!$formdata = data_submitted() or !confirm_sesskey()) {
cc03871b 1818 return;
1819 }
1820
1821 $data = array();
fcac8e51 1822 $grading_info = grade_get_grades($this->course->id, 'mod', 'assignment', $this->assignment->id, $userid);
1823
1824 if (!empty($grading_info->outcomes)) {
d886a7ea 1825 foreach($grading_info->outcomes as $n=>$old) {
1826 $name = 'outcome_'.$n;
1827 if (isset($formdata->{$name}[$userid]) and $old->grades[$userid]->grade != $formdata->{$name}[$userid]) {
1828 $data[$n] = $formdata->{$name}[$userid];
cc03871b 1829 }
1830 }
1831 }
1832 if (count($data) > 0) {
1833 grade_update_outcomes('mod/assignment', $this->course->id, 'mod', 'assignment', $this->assignment->id, $userid, $data);
1834 }
1835
1836 }
1837
7af1e882 1838 /**
1839 * Load the submission object for a particular user
1840 *
256578f6 1841 * @global object
1842 * @global object
75cf84ac
RW
1843 * @param int $userid int The id of the user whose submission we want or 0 in which case USER->id is used
1844 * @param bool $createnew boolean optional Defaults to false. If set to true a new submission object will be created in the database
03076be4 1845 * @param bool $teachermodified student submission set if false
90310b1b 1846 * @return object|bool The submission or false (if $createnew is false and there is no existing submission).
7af1e882 1847 */
03076be4 1848 function get_submission($userid=0, $createnew=false, $teachermodified=false) {
5053f00f 1849 global $USER, $DB;
f77cfb73 1850
1851 if (empty($userid)) {
1852 $userid = $USER->id;
1853 }
1854
5053f00f 1855 $submission = $DB->get_record('assignment_submissions', array('assignment'=>$this->assignment->id, 'userid'=>$userid));
d699cd1e 1856
75cf84ac 1857 if ($submission) {
b0f2597e 1858 return $submission;
90310b1b 1859 } else if (!$createnew) {
75cf84ac 1860 return false;
b0f2597e 1861 }
03076be4 1862 $newsubmission = $this->prepare_new_submission($userid, $teachermodified);
7826abc7 1863 $DB->insert_record("assignment_submissions", $newsubmission);
d699cd1e 1864
5053f00f 1865 return $DB->get_record('assignment_submissions', array('assignment'=>$this->assignment->id, 'userid'=>$userid));
b0f2597e 1866 }
d699cd1e 1867
ad2d5eba
GGC
1868 /**
1869 * Check the given submission is complete. Preliminary rows are often created in the assignment_submissions
1870 * table before a submission actually takes place. This function checks to see if the given submission has actually
1871 * been submitted.
1872 *
1873 * @param stdClass $submission The submission we want to check for completion
1874 * @return bool Indicates if the submission was found to be complete
1875 */
1876 public function is_submitted_with_required_data($submission) {
1877 return $submission->timemodified;
1878 }
1879
7af1e882 1880 /**
1881 * Instantiates a new submission object for a given user
1882 *
1883 * Sets the assignment, userid and times, everything else is set to default values.
256578f6 1884 *
1885 * @param int $userid The userid for which we want a submission object
03076be4 1886 * @param bool $teachermodified student submission set if false
7af1e882 1887 * @return object The submission
1888 */
03076be4 1889 function prepare_new_submission($userid, $teachermodified=false) {
39790bd8 1890 $submission = new stdClass();
39e11905 1891 $submission->assignment = $this->assignment->id;
1892 $submission->userid = $userid;
47c96a77 1893 $submission->timecreated = time();
16fc2088 1894 // teachers should not be modifying modified date, except offline assignments
03076be4 1895 if ($teachermodified) {
1896 $submission->timemodified = 0;
1897 } else {
1898 $submission->timemodified = $submission->timecreated;
1899 }
39e11905 1900 $submission->numfiles = 0;
1901 $submission->data1 = '';
1902 $submission->data2 = '';
1903 $submission->grade = -1;
ea6432fe 1904 $submission->submissioncomment = '';
39e11905 1905 $submission->format = 0;
1906 $submission->teacher = 0;
1907 $submission->timemarked = 0;
1908 $submission->mailed = 0;
1909 return $submission;
1910 }
1911
7af1e882 1912 /**
1913 * Return all assignment submissions by ENROLLED students (even empty)
1914 *
256578f6 1915 * @param string $sort optional field names for the ORDER BY in the sql query
1916 * @param string $dir optional specifying the sort direction, defaults to DESC
7af1e882 1917 * @return array The submission objects indexed by id
1918 */
b0f2597e 1919 function get_submissions($sort='', $dir='DESC') {
7af1e882 1920 return assignment_get_all_submissions($this->assignment, $sort, $dir);
b0f2597e 1921 }
48c6ebeb 1922
7af1e882 1923 /**
8caba229 1924 * Counts all complete (real) assignment submissions by enrolled students
7af1e882 1925 *
8caba229
GGC
1926 * @param int $groupid (optional) If nonzero then count is restricted to this group
1927 * @return int The number of submissions
7af1e882 1928 */
b0f2597e 1929 function count_real_submissions($groupid=0) {
8caba229
GGC
1930 global $CFG;
1931 global $DB;
1932
1933 // Grab the context assocated with our course module
01a67102 1934 $context = context_module::instance($this->cm->id);
8caba229
GGC
1935
1936 // Get ids of users enrolled in the given course.
1937 list($enroledsql, $params) = get_enrolled_sql($context, 'mod/assignment:view', $groupid);
1938 $params['assignmentid'] = $this->cm->instance;
1939
1940 // Get ids of users enrolled in the given course.
1941 return $DB->count_records_sql("SELECT COUNT('x')
1942 FROM {assignment_submissions} s
1943 LEFT JOIN {assignment} a ON a.id = s.assignment
1944 INNER JOIN ($enroledsql) u ON u.id = s.userid
1945 WHERE s.assignment = :assignmentid AND
1946 s.timemodified > 0", $params);
d59269cf 1947 }
d699cd1e 1948
7af1e882 1949 /**
1950 * Alerts teachers by email of new or changed assignments that need grading
1951 *
1952 * First checks whether the option to email teachers is set for this assignment.
1953 * Sends an email to ALL teachers in the course (or in the group if using separate groups).
1954 * Uses the methods email_teachers_text() and email_teachers_html() to construct the content.
256578f6 1955 *
1956 * @global object
1957 * @global object
7af1e882 1958 * @param $submission object The submission that has changed
256578f6 1959 * @return void
7af1e882 1960 */
73097f07 1961 function email_teachers($submission) {
5053f00f 1962 global $CFG, $DB;
73097f07 1963
d8199f1d 1964 if (empty($this->assignment->emailteachers)) { // No need to do anything
73097f07 1965 return;
1966 }
1967
5053f00f 1968 $user = $DB->get_record('user', array('id'=>$submission->userid));
73097f07 1969
413efd22 1970 if ($teachers = $this->get_graders($user)) {
73097f07 1971
1972 $strassignments = get_string('modulenameplural', 'assignment');
1973 $strassignment = get_string('modulename', 'assignment');
1974 $strsubmitted = get_string('submitted', 'assignment');
1975
1976 foreach ($teachers as $teacher) {
39790bd8 1977 $info = new stdClass();
413efd22 1978 $info->username = fullname($user, true);
d8199f1d 1979 $info->assignment = format_string($this->assignment->name,true);
1980 $info->url = $CFG->wwwroot.'/mod/assignment/submissions.php?id='.$this->cm->id;
92d0dd9f 1981 $info->timeupdated = userdate($submission->timemodified, '%c', $teacher->timezone);
d8199f1d 1982
1983 $postsubject = $strsubmitted.': '.$info->username.' -> '.$this->assignment->name;
1984 $posttext = $this->email_teachers_text($info);
1985 $posthtml = ($teacher->mailformat == 1) ? $this->email_teachers_html($info) : '';
73097f07 1986
39790bd8 1987 $eventdata = new stdClass();
3b120e46 1988 $eventdata->modulename = 'assignment';
1989 $eventdata->userfrom = $user;
1990 $eventdata->userto = $teacher;
1991 $eventdata->subject = $postsubject;
1992 $eventdata->fullmessage = $posttext;
1993 $eventdata->fullmessageformat = FORMAT_PLAIN;
1994 $eventdata->fullmessagehtml = $posthtml;
fa09b5a9 1995 $eventdata->smallmessage = $postsubject;
192bcd76 1996
39e171ac 1997 $eventdata->name = 'assignment_updates';
192bcd76 1998 $eventdata->component = 'mod_assignment';
39e171ac 1999 $eventdata->notification = 1;
6217809c
AB
2000 $eventdata->contexturl = $info->url;
2001 $eventdata->contexturlname = $info->assignment;
54c37fbd 2002
7c7d3afa 2003 message_send($eventdata);
73097f07 2004 }
2005 }
2006 }
2007
256578f6 2008 /**
261cbbac
DM
2009 * Sends a file
2010 *
256578f6 2011 * @param string $filearea
2012 * @param array $args
261cbbac
DM
2013 * @param bool $forcedownload whether or not force download
2014 * @param array $options additional options affecting the file serving
256578f6 2015 * @return bool
2016 */
261cbbac 2017 function send_file($filearea, $args, $forcedownload, array $options=array()) {
172dd12c 2018 debugging('plugin does not implement file sending', DEBUG_DEVELOPER);
2019 return false;
2020 }
2021
413efd22 2022 /**
2023 * Returns a list of teachers that should be grading given submission
256578f6 2024 *
2025 * @param object $user
2026 * @return array
413efd22 2027 */
2028 function get_graders($user) {
d402ee1c
CF
2029 global $DB;
2030
413efd22 2031 //potential graders
d402ee1c
CF
2032 list($enrolledsql, $params) = get_enrolled_sql($this->context, 'mod/assignment:grade', 0, true);
2033 $sql = "SELECT u.*
2034 FROM {user} u
2035 JOIN ($enrolledsql) je ON je.id = u.id";
2036 $potgraders = $DB->get_records_sql($sql, $params);
7bddd4b7 2037
413efd22 2038 $graders = array();
ba3dc7b4 2039 if (groups_get_activity_groupmode($this->cm) == SEPARATEGROUPS) { // Separate groups are being used
2c386f82 2040 if ($groups = groups_get_all_groups($this->course->id, $user->id)) { // Try to find all groups
413efd22 2041 foreach ($groups as $group) {
2042 foreach ($potgraders as $t) {
2043 if ($t->id == $user->id) {
2044 continue; // do not send self
2045 }
2046 if (groups_is_member($group->id, $t->id)) {
2047 $graders[$t->id] = $t;
2048 }
2049 }
2050 }
2051 } else {
2052 // user not in group, try to find graders without group
2053 foreach ($potgraders as $t) {
2054 if ($t->id == $user->id) {
2055 continue; // do not send self
2056 }
2c386f82 2057 if (!groups_get_all_groups($this->course->id, $t->id)) { //ugly hack
413efd22 2058 $graders[$t->id] = $t;
2059 }
2060 }
2061 }
2062 } else {
2063 foreach ($potgraders as $t) {
2064 if ($t->id == $user->id) {
2065 continue; // do not send self
2066 }
2067 $graders[$t->id] = $t;
2068 }
2069 }
2070 return $graders;
2071 }
2072
7af1e882 2073 /**
2074 * Creates the text content for emails to teachers
2075 *
2076 * @param $info object The info used by the 'emailteachermail' language string
2077 * @return string
2078 */
d8199f1d 2079 function email_teachers_text($info) {
8ebbb06a
SH
2080 $posttext = format_string($this->course->shortname, true, array('context' => $this->coursecontext)).' -> '.
2081 $this->strassignments.' -> '.
2082 format_string($this->assignment->name, true, array('context' => $this->context))."\n";
d8199f1d 2083 $posttext .= '---------------------------------------------------------------------'."\n";
2084 $posttext .= get_string("emailteachermail", "assignment", $info)."\n";
73963212 2085 $posttext .= "\n---------------------------------------------------------------------\n";
d8199f1d 2086 return $posttext;
2087 }
2088
7af1e882 2089 /**
2090 * Creates the html content for emails to teachers
2091 *
2092 * @param $info object The info used by the 'emailteachermailhtml' language string
2093 * @return string
2094 */
d8199f1d 2095 function email_teachers_html($info) {
3554b5c2 2096 global $CFG;
d8199f1d 2097 $posthtml = '<p><font face="sans-serif">'.
8ebbb06a 2098 '<a href="'.$CFG->wwwroot.'/course/view.php?id='.$this->course->id.'">'.format_string($this->course->shortname, true, array('context' => $this->coursecontext)).'</a> ->'.
d8199f1d 2099 '<a href="'.$CFG->wwwroot.'/mod/assignment/index.php?id='.$this->course->id.'">'.$this->strassignments.'</a> ->'.
8ebbb06a 2100 '<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 2101 $posthtml .= '<hr /><font face="sans-serif">';
2102 $posthtml .= '<p>'.get_string('emailteachermailhtml', 'assignment', $info).'</p>';
2103 $posthtml .= '</font><hr />';
815b5ca6 2104 return $posthtml;
d8199f1d 2105 }
2106
7af1e882 2107 /**
2108 * Produces a list of links to the files uploaded by a user
2109 *
2110 * @param $userid int optional id of the user. If 0 then $USER->id is used.
2111 * @param $return boolean optional defaults to false. If true the list is returned rather than printed
2112 * @return string optional
2113 */
d8199f1d 2114 function print_user_files($userid=0, $return=false) {
d436d197 2115 global $CFG, $USER, $OUTPUT;
45fa3412 2116
d8199f1d 2117 if (!$userid) {
2118 if (!isloggedin()) {
2119 return '';
2120 }
2121 $userid = $USER->id;
2122 }
45fa3412 2123
73097f07 2124 $output = '';
45fa3412 2125
31f56ef6 2126 $submission = $this->get_submission($userid);
6708a1f5
SH
2127 if (!$submission) {
2128 return $output;
2129 }
31f56ef6 2130
6708a1f5
SH
2131 $fs = get_file_storage();
2132 $files = $fs->get_area_files($this->context->id, 'mod_assignment', 'submission', $submission->id, "timemodified", false);
2133 if (!empty($files)) {
24ba58ee 2134 require_once($CFG->dirroot . '/mod/assignment/locallib.php');
6708a1f5
SH
2135 if ($CFG->enableportfolios) {
2136 require_once($CFG->libdir.'/portfoliolib.php');
2137 $button = new portfolio_add_button();
2138 }
172dd12c 2139 foreach ($files as $file) {
2140 $filename = $file->get_filename();
172dd12c 2141 $mimetype = $file->get_mimetype();
437239d1 2142 $path = file_encode_url($CFG->wwwroot.'/pluginfile.php', '/'.$this->context->id.'/mod_assignment/submission/'.$submission->id.'/'.$filename);
559276b1 2143 $output .= '<a href="'.$path.'" >'.$OUTPUT->pix_icon(file_file_icon($file), get_mimetype_description($file), 'moodle', array('class' => 'icon')).s($filename).'</a>';
6708a1f5 2144 if ($CFG->enableportfolios && $this->portfolio_exportable() && has_capability('mod/assignment:exportownsubmission', $this->context)) {
37743241
MN
2145 $button->set_callback_options('assignment_portfolio_caller',
2146 array('id' => $this->cm->id, 'submissionid' => $submission->id, 'fileid' => $file->get_id()),
2147 'mod_assignment');
887160c7 2148 $button->set_format_by_file($file);
0d06b6fd 2149 $output .= $button->to_html(PORTFOLIO_ADD_ICON_LINK);
73097f07 2150 }
c676af9f 2151
19f7391c
SB
2152 if ($CFG->enableplagiarism) {
2153 require_once($CFG->libdir.'/plagiarismlib.php');
2154 $output .= plagiarism_get_links(array('userid'=>$userid, 'file'=>$file, 'cmid'=>$this->cm->id, 'course'=>$this->course, 'assignment'=>$this->assignment));
2155 $output .= '<br />';
2156 }
172dd12c 2157 }
6057bf5b 2158 if ($CFG->enableportfolios && count($files) > 1 && $this->portfolio_exportable() && has_capability('mod/assignment:exportownsubmission', $this->context)) {
37743241
MN
2159 $button->set_callback_options('assignment_portfolio_caller',
2160 array('id' => $this->cm->id, 'submissionid' => $submission->id),
2161 'mod_assignment');
b777c798 2162 $output .= '<br />' . $button->to_html(PORTFOLIO_ADD_TEXT_LINK);
73097f07 2163 }
2164 }
2165
2166 $output = '<div class="files">'.$output.'</div>';
2167
2168 if ($return) {
2169 return $output;
2170 }
2171 echo $output;
2172 }
2173
7af1e882 2174 /**
2175 * Count the files uploaded by a given user
2176 *
b5e1ffe4 2177 * @param $itemid int The submission's id as the file's itemid.
7af1e882 2178 * @return int
2179 */
b5e1ffe4 2180 function count_user_files($itemid) {
172dd12c 2181 $fs = get_file_storage();
b5e1ffe4 2182 $files = $fs->get_area_files($this->context->id, 'mod_assignment', 'submission', $itemid, "id", false);
172dd12c 2183 return count($files);
73097f07 2184 }
2185
7af1e882 2186 /**
2187 * Returns true if the student is allowed to submit
2188 *
2189 * Checks that the assignment has started and, if the option to prevent late
2190 * submissions is set, also checks that the assignment has not yet closed.
2191 * @return boolean
2192 */
f77cfb73 2193 function isopen() {
2194 $time = time();
1e4343a0 2195 if ($this->assignment->preventlate && $this->assignment->timedue) {
f77cfb73 2196 return ($this->assignment->timeavailable <= $time && $time <= $this->assignment->timedue);
2197 } else {
2198 return ($this->assignment->timeavailable <= $time);
2199 }
2200 }
2201
0b5a80a1 2202
2203 /**
dc6cb74e 2204 * Return true if is set description is hidden till available date
2205 *
0b5a80a1 2206 * This is needed by calendar so that hidden descriptions do not
dc6cb74e 2207 * come up in upcoming events.
2208 *
0b5a80a1 2209 * Check that description is hidden till available date
dc6cb74e 2210 * By default return false
2211 * Assignments types should implement this method if needed
2212 * @return boolen
0b5a80a1 2213 */
dc6cb74e 2214 function description_is_hidden() {
2215 return false;
2216 }
2217
7af1e882 2218 /**
2219 * Return an outline of the user's interaction with the assignment
2220 *
2221 * The default method prints the grade and timemodified
1a96363a 2222 * @param $grade object
7af1e882 2223 * @return object with properties ->info and ->time
2224 */
1a96363a 2225 function user_outline($grade) {
39e11905 2226
39790bd8 2227 $result = new stdClass();
1a96363a
NC
2228 $result->info = get_string('grade').': '.$grade->str_long_grade;
2229 $result->time = $grade->dategraded;
2230 return $result;
73097f07 2231 }
7af1e882 2232
2233 /**
2234 * Print complete information about the user's interaction with the assignment
2235 *
2236 * @param $user object
2237 */
1a96363a 2238 function user_complete($user, $grade=null) {
3a003ead 2239 global $OUTPUT;
1a96363a 2240
73097f07 2241 if ($submission = $this->get_submission($user->id)) {
172dd12c 2242
2243 $fs = get_file_storage();
26a9dc72 2244
87f702a0 2245 if ($files = $fs->get_area_files($this->context->id, 'mod_assignment', 'submission', $submission->id, "timemodified", false)) {
172dd12c 2246 $countfiles = count($files)." ".get_string("uploadedfiles", "assignment");
2247 foreach ($files as $file) {
2248 $countfiles .= "; ".$file->get_filename();
73097f07 2249 }
2250 }
45fa3412 2251
3a003ead 2252 echo $OUTPUT->box_start();
73097f07 2253 echo get_string("lastmodified").": ";
9bf660b3 2254 echo userdate($submission->timemodified);
2255 echo $this->display_lateness($submission->timemodified);
45fa3412 2256
70b2c772 2257 $this->print_user_files($user->id);
45fa3412 2258
73097f07 2259 echo '<br />';
45fa3412 2260
1a96363a 2261 $this->view_feedback($submission);
45fa3412 2262
3a003ead 2263 echo $OUTPUT->box_end();
45fa3412 2264
73097f07 2265 } else {
156d6f48
MG
2266 if ($grade) {
2267 echo $OUTPUT->container(get_string('grade').': '.$grade->str_long_grade);
2268 if ($grade->str_feedback) {
2269 echo $OUTPUT->container(get_string('feedback').': '.$grade->str_feedback);
2270 }
2271 }
73097f07 2272 print_string("notsubmittedyet", "assignment");
2273 }
2274 }
2275
7af1e882 2276 /**
2277 * Return a string indicating how late a submission is
2278 *
45fa3412 2279 * @param $timesubmitted int
7af1e882 2280 * @return string
2281 */
70b2c772 2282 function display_lateness($timesubmitted) {
76a60031 2283 return assignment_display_lateness($timesubmitted, $this->assignment->timedue);
73097f07 2284 }
2285
55b4d096 2286 /**
2287 * Empty method stub for all delete actions.
2288 */
2289 function delete() {
2290 //nothing by default
2291 redirect('view.php?id='.$this->cm->id);
2292 }
2293
2294 /**
2295 * Empty custom feedback grading form.
2296 */
2297 function custom_feedbackform($submission, $return=false) {
2298 //nothing by default
2299 return '';
2300 }
73097f07 2301
09ba8e56 2302 /**
2303 * Add a get_coursemodule_info function in case any assignment type wants to add 'extra' information
2304 * for the course (see resource).
2305 *
206ab184 2306 * Given a course_module object, this function returns any "extra" information that may be needed
09ba8e56 2307 * when printing this activity in a course listing. See get_array_of_activities() in course/lib.php.
206ab184 2308 *
09ba8e56 2309 * @param $coursemodule object The coursemodule object (record).
3e4c2435 2310 * @return cached_cm_info Object used to customise appearance on course page
09ba8e56 2311 */
2312 function get_coursemodule_info($coursemodule) {
3e4c2435 2313 return null;
09ba8e56 2314 }
2315
d014b69b 2316 /**
2317 * Plugin cron method - do not use $this here, create new assignment instances if needed.
2318 * @return void
2319 */
2320 function cron() {
2321 //no plugin cron by default - override if needed
2322 }
2323
0b5a80a1 2324 /**
2325 * Reset all submissions
2326 */
2327 function reset_userdata($data) {
5053f00f 2328 global $CFG, $DB;
0b5a80a1 2329
74d7d735 2330 if (!$DB->count_records('assignment', array('course'=>$data->courseid, 'assignmenttype'=>$this->type))) {
0b5a80a1 2331 return array(); // no assignments of this type present
2332 }
2333
2334 $componentstr = get_string('modulenameplural', 'assignment');
2335 $status = array();
2336
2337 $typestr = get_string('type'.$this->type, 'assignment');
40fcf70c
DP
2338 // ugly hack to support pluggable assignment type titles...
2339 if($typestr === '[[type'.$this->type.']]'){
2340 $typestr = get_string('type'.$this->type, 'assignment_'.$this->type);
2341 }
0b5a80a1 2342
2343 if (!empty($data->reset_assignment_submissions)) {
2344 $assignmentssql = "SELECT a.id
5053f00f 2345 FROM {assignment} a
2346 WHERE a.course=? AND a.assignmenttype=?";
2347 $params = array($data->courseid, $this->type);
0b5a80a1 2348
75dfe830 2349 // now get rid of all submissions and responses
4e866d5e 2350 $fs = get_file_storage();
5053f00f 2351 if ($assignments = $DB->get_records_sql($assignmentssql, $params)) {
0b5a80a1 2352 foreach ($assignments as $assignmentid=>$unused) {
4e866d5e 2353 if (!$cm = get_coursemodule_from_instance('assignment', $assignmentid)) {
2354 continue;
2355 }
01a67102 2356 $context = context_module::instance($cm->id);
64f93798
PS
2357 $fs->delete_area_files($context->id, 'mod_assignment', 'submission');
2358 $fs->delete_area_files($context->id, 'mod_assignment', 'response');
0b5a80a1 2359 }
2360 }
2361
75dfe830 2362 $DB->delete_records_select('assignment_submissions', "assignment IN ($assignmentssql)", $params);
2363
0b5a80a1 2364 $status[] = array('component'=>$componentstr, 'item'=>get_string('deleteallsubmissions','assignment').': '.$typestr, 'error'=>false);
dd97c328 2365
0b5a80a1 2366 if (empty($data->reset_gradebook_grades)) {
2367 // remove all grades from gradebook
2368 assignment_reset_gradebook($data->courseid, $this->type);
2369 }
2370 }
2371
2372 /// updating dates - shift may be negative too
2373 if ($data->timeshift) {
2374 shift_course_mod_dates('assignment', array('timedue', 'timeavailable'), $data->timeshift, $data->courseid);
2375 $status[] = array('component'=>$componentstr, 'item'=>get_string('datechanged').': '.$typestr, 'error'=>false);
2376 }
2377
2378 return $status;
2379 }
67a87e7d 2380
2381
2382 function portfolio_exportable() {
2383 return false;
2384 }
3b804d2d 2385
2386 /**
2387 * base implementation for backing up subtype specific information
2388 * for one single module
2389 *
2390 * @param filehandle $bf file handle for xml file to write to
2391 * @param mixed $preferences the complete backup preference object
2392 *
2393 * @return boolean
2394 *
2395 * @static
2396 */
2397 static function backup_one_mod($bf, $preferences, $assignment) {
2398 return true;
2399 }
2400
2401 /**
2402 * base implementation for backing up subtype specific information
2403 * for one single submission
2404 *
2405 * @param filehandle $bf file handle for xml file to write to
2406 * @param mixed $preferences the complete backup preference object
2407 * @param object $submission the assignment submission db record
2408 *
2409 * @return boolean
2410 *
2411 * @static
2412 */
2413 static function backup_one_submission($bf, $preferences, $assignment, $submission) {
2414 return true;
2415 }
2416
2417 /**
2418 * base implementation for restoring subtype specific information
2419 * for one single module
2420 *
2421 * @param array $info the array representing the xml
2422 * @param object $restore the restore preferences
2423 *
2424 * @return boolean
2425 *
2426 * @static
2427 */
2428 static function restore_one_mod($info, $restore, $assignment) {
2429 return true;
2430 }
2431
2432 /**
2433 * base implementation for restoring subtype specific information
2434 * for one single submission
2435 *
2436 * @param object $submission the newly created submission
2437 * @param array $info the array representing the xml
2438 * @param object $restore the restore preferences
2439 *
2440 * @return boolean
2441 *
2442 * @static
2443 */
2444 static function restore_one_submission($info, $restore, $assignment, $submission) {
2445 return true;
2446 }
2447
b0f2597e 2448} ////// End of the assignment_base class
d699cd1e 2449
04eba58f 2450
6b8b0b2e 2451class assignment_grading_form extends moodleform {
3c2b3cb3
MG
2452 /** @var stores the advaned grading instance (if used in grading) */
2453 private $advancegradinginstance;
d2b6ee29 2454
2455 function definition() {
2456 global $OUTPUT;
2457 $mform =& $this->_form;
2458
36937f02
MG
2459 if (isset($this->_customdata->advancedgradinginstance)) {
2460 $this->use_advanced_grading($this->_customdata->advancedgradinginstance);
18e6298c
MG
2461 }
2462
d2b6ee29 2463 $formattr = $mform->getAttributes();
2464 $formattr['id'] = 'submitform';
2465 $mform->setAttributes($formattr);
2466 // hidden params
2467 $mform->addElement('hidden', 'offset', ($this->_customdata->offset+1));
2468 $mform->setType('offset', PARAM_INT);
2469 $mform->addElement('hidden', 'userid', $this->_customdata->userid);
2470 $mform->setType('userid', PARAM_INT);
2471 $mform->addElement('hidden', 'nextid', $this->_customdata->nextid);
2472 $mform->setType('nextid', PARAM_INT);
2473 $mform->addElement('hidden', 'id', $this->_customdata->cm->id);
2474 $mform->setType('id', PARAM_INT);
2475 $mform->addElement('hidden', 'sesskey', sesskey());
2476 $mform->setType('sesskey', PARAM_ALPHANUM);
2477 $mform->addElement('hidden', 'mode', 'grade');
2d274675 2478 $mform->setType('mode', PARAM_TEXT);
d2b6ee29 2479 $mform->addElement('hidden', 'menuindex', "0");
2480 $mform->setType('menuindex', PARAM_INT);
2481 $mform->addElement('hidden', 'saveuserid', "-1");
2482 $mform->setType('saveuserid', PARAM_INT);
fdb797ad
RW
2483 $mform->addElement('hidden', 'filter', "0");
2484 $mform->setType('filter', PARAM_INT);
d2b6ee29 2485
2486 $mform->addElement('static', 'picture', $OUTPUT->user_picture($this->_customdata->user),
2487 fullname($this->_customdata->user, true) . '<br/>' .
2488 userdate($this->_customdata->submission->timemodified) .
2489 $this->_customdata->lateness );
2490
291ee134 2491 $this->add_submission_content();
d2b6ee29 2492 $this->add_grades_section();
2493
2494 $this->add_feedback_section();
2495
261b585d 2496 if ($this->_customdata->submission->timemarked) {
291ee134 2497 $datestring = userdate($this->_customdata->submission->timemarked)."&nbsp; (".format_time(time() - $this->_customdata->submission->timemarked).")";
d2b6ee29 2498 $mform->addElement('header', 'Last Grade', get_string('lastgrade', 'assignment'));
2499 $mform->addElement('static', 'picture', $OUTPUT->user_picture($this->_customdata->teacher) ,
2500 fullname($this->_customdata->teacher,true).
291ee134 2501 '<br/>'.$datestring);
d2b6ee29 2502 }
2503 // buttons
2504 $this->add_action_buttons();
2505
d2b6ee29 2506 }
2507
18e6298c 2508 /**
36937f02 2509 * Gets or sets the instance for advanced grading
18e6298c 2510 *
36937f02 2511 * @param gradingform_instance $gradinginstance
18e6298c 2512 */
36937f02
MG
2513 public function use_advanced_grading($gradinginstance = false) {
2514 if ($gradinginstance !== false) {
2515 $this->advancegradinginstance = $gradinginstance;
18e6298c 2516 }
36937f02 2517 return $this->advancegradinginstance;
18e6298c
MG
2518 }
2519
a153c9f2
AD
2520 /**
2521 * Add the grades configuration section to the assignment configuration form
2522 */
d2b6ee29 2523 function add_grades_section() {
2524 global $CFG;
2525 $mform =& $this->_form;
2526 $attributes = array();
261b585d 2527 if ($this->_customdata->gradingdisabled) {
2528 $attributes['disabled'] ='disabled';
2529 }
d2b6ee29 2530
d2b6ee29 2531 $mform->addElement('header', 'Grades', get_string('grades', 'grades'));
fba356f3 2532
d2b6ee29 2533 $grademenu = make_grades_menu($this->_customdata->assignment->grade);
36937f02 2534 if ($gradinginstance = $this->use_advanced_grading()) {
9e2eca0f 2535 $gradinginstance->get_controller()->set_grade_range($grademenu);
71380f2f
MG
2536 $gradingelement = $mform->addElement('grading', 'advancedgrading', get_string('grade').':', array('gradinginstance' => $gradinginstance));
2537 if ($this->_customdata->gradingdisabled) {
2538 $gradingelement->freeze();
2539 } else {
2540 $mform->addElement('hidden', 'advancedgradinginstanceid', $gradinginstance->get_id());
2541 }
fba356f3
DM
2542 } else {
2543 // use simple direct grading
fba356f3 2544 $grademenu['-1'] = get_string('nograde');
d2b6ee29 2545
fba356f3
DM
2546 $mform->addElement('select', 'xgrade', get_string('grade').':', $grademenu, $attributes);
2547 $mform->setDefault('xgrade', $this->_customdata->submission->grade ); //@fixme some bug when element called 'grade' makes it break
2548 $mform->setType('xgrade', PARAM_INT);
2549 }
d2b6ee29 2550
261b585d 2551 if (!empty($this->_customdata->enableoutcomes)) {
d2b6ee29 2552 foreach($this->_customdata->grading_info->outcomes as $n=>$outcome) {
2553 $options = make_grades_menu(-$outcome->scaleid);
2554 if ($outcome->grades[$this->_customdata->submission->userid]->locked) {
2555 $options[0] = get_string('nooutcome', 'grades');
8545f86c
MG
2556 $mform->addElement('static', 'outcome_'.$n.'['.$this->_customdata->userid.']', $outcome->name.':',
2557 $options[$outcome->grades[$this->_customdata->submission->userid]->grade]);
d2b6ee29 2558 } else {
2559 $options[''] = get_string('nooutcome', 'grades');
2560 $attributes = array('id' => 'menuoutcome_'.$n );
2561 $mform->addElement('select', 'outcome_'.$n.'['.$this->_customdata->userid.']', $outcome->name.':', $options, $attributes );
2562 $mform->setType('outcome_'.$n.'['.$this->_customdata->userid.']', PARAM_INT);
2563 $mform->setDefault('outcome_'.$n.'['.$this->_customdata->userid.']', $outcome->grades[$this->_customdata->submission->userid]->grade );
2564 }
2565 }
2566 }
01a67102 2567 $course_context = context_module::instance($this->_customdata->cm->id);
753c1de5 2568 if (has_capability('gradereport/grader:view', $course_context) && has_capability('moodle/grade:viewall', $course_context)) {
2569 $grade = '<a href="'.$CFG->wwwroot.'/grade/report/grader/index.php?id='. $this->_customdata->courseid .'" >'.
2570 $this->_customdata->grading_info->items[0]->grades[$this->_customdata->userid]->str_grade . '</a>';
2571 }else{
2572 $grade = $this->_customdata->grading_info->items[0]->grades[$this->_customdata->userid]->str_grade;
2573 }
2574 $mform->addElement('static', 'finalgrade', get_string('currentgrade', 'assignment').':' ,$grade);
d2b6ee29 2575 $mform->setType('finalgrade', PARAM_INT);
2576 }
2577
2578 /**
2579 *
2580 * @global core_renderer $OUTPUT
2581 */
2582 function add_feedback_section() {
2583 global $OUTPUT;
2584 $mform =& $this->_form;
2585 $mform->addElement('header', 'Feed Back', get_string('feedback', 'grades'));
2586
261b585d 2587 if ($this->_customdata->gradingdisabled) {
d2b6ee29 2588 $mform->addElement('static', 'disabledfeedback', $this->_customdata->grading_info->items[0]->grades[$this->_customdata->userid]->str_feedback );
2589 } else {
2590 // visible elements
2591
2592 $mform->addElement('editor', 'submissioncomment_editor', get_string('feedback', 'assignment').':', null, $this->get_editor_options() );
2593 $mform->setType('submissioncomment_editor', PARAM_RAW); // to be cleaned before display
2594 $mform->setDefault('submissioncomment_editor', $this->_customdata->submission->submissioncomment);
2595 //$mform->addRule('submissioncomment', get_string('required'), 'required', null, 'client');
291ee134
AB
2596 switch ($this->_customdata->assignment->assignmenttype) {
2597 case 'upload' :
2598 case 'uploadsingle' :
2599 $mform->addElement('filemanager', 'files_filemanager', get_string('responsefiles', 'assignment'). ':', null, $this->_customdata->fileui_options);
2600 break;
2601 default :
2602 break;
2603 }
d2b6ee29 2604 $mform->addElement('hidden', 'mailinfo_h', "0");
2605 $mform->setType('mailinfo_h', PARAM_INT);
be34802d
AD
2606 $mform->addElement('checkbox', 'mailinfo',get_string('enablenotification','assignment').
2607 $OUTPUT->help_icon('enablenotification', 'assignment') .':' );
d2b6ee29 2608 $mform->setType('mailinfo', PARAM_INT);
2609 }
2610 }
2611
e7755fc6 2612 function add_action_buttons($cancel = true, $submitlabel = NULL) {
d2b6ee29 2613 $mform =& $this->_form;
d2b6ee29 2614 //if there are more to be graded.
261b585d 2615 if ($this->_customdata->nextid>0) {
d2b6ee29 2616 $buttonarray=array();
2617 $buttonarray[] = &$mform->createElement('submit', 'submitbutton', get_string('savechanges'));
2618 //@todo: fix accessibility: javascript dependency not necessary
2619 $buttonarray[] = &$mform->createElement('submit', 'saveandnext', get_string('saveandnext'));
2620 $buttonarray[] = &$mform->createElement('submit', 'next', get_string('next'));
2621 $buttonarray[] = &$mform->createElement('cancel');
2622 } else {
2623 $buttonarray=array();
2624 $buttonarray[] = &$mform->createElement('submit', 'submitbutton', get_string('savechanges'));
2625 $buttonarray[] = &$mform->createElement('cancel');
2626 }
2627 $mform->addGroup($buttonarray, 'grading_buttonar', '', array(' '), false);
291ee134 2628 $mform->closeHeaderBefore('grading_buttonar');
d2b6ee29 2629 $mform->setType('grading_buttonar', PARAM_RAW);
2630 }
2631
2632 function add_submission_content() {
2633 $mform =& $this->_form;
2634 $mform->addElement('header', 'Submission', get_string('submission', 'assignment'));
2635 $mform->addElement('static', '', '' , $this->_customdata->submission_content );
2636 }
96f4a64b 2637
d2b6ee29 2638 protected function get_editor_options() {
2639 $editoroptions = array();
64f93798
PS
2640 $editoroptions['component'] = 'mod_assignment';
2641 $editoroptions['filearea'] = 'feedback';
d2b6ee29 2642 $editoroptions['noclean'] = false;
64f93798 2643 $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 2644 $editoroptions['maxbytes'] = $this->_customdata->maxbytes;
e9de1cf4 2645 $editoroptions['context'] = $this->_customdata->context;
d2b6ee29 2646 return $editoroptions;
2647 }
2648
2649 public function set_data($data) {
2650 $editoroptions = $this->get_editor_options();
2651 if (!isset($data->text)) {
2652 $data->text = '';
2653 }
2654 if (!isset($data->format)) {
2655 $data->textformat = FORMAT_HTML;
2656 } else {
2657 $data->textformat = $data->format;
2658 }
2659
2660 if (!empty($this->_customdata->submission->id)) {
2661 $itemid = $this->_customdata->submission->id;
2662 } else {
2663 $itemid = null;
2664 }
2665
291ee134
AB
2666 switch ($this->_customdata->assignment->assignmenttype) {
2667 case 'upload' :
2668 case 'uploadsingle' :
2669 $data = file_prepare_standard_filemanager($data, 'files', $editoroptions, $this->_customdata->context, 'mod_assignment', 'response', $itemid);
2670 break;
2671 default :
2672 break;
2673 }
2674
64f93798 2675 $data = file_prepare_standard_editor($data, 'submissioncomment', $editoroptions, $this->_customdata->context, $editoroptions['component'], $editoroptions['filearea'], $itemid);
d2b6ee29 2676 return parent::set_data($data);
2677 }
2678
2679 public function get_data() {
2680 $data = parent::get_data();
2681
2682 if (!empty($this->_customdata->submission->id)) {
2683 $itemid = $this->_customdata->submission->id;
2684 } else {
64f93798 2685 $itemid = null; //TODO: this is wrong, itemid MUST be known when saving files!! (skodak)
d2b6ee29 2686 }
2687
2688 if ($data) {
2689 $editoroptions = $this->get_editor_options();
291ee134
AB
2690 switch ($this->_customdata->assignment->assignmenttype) {
2691 case 'upload' :
2692 case 'uploadsingle' :
2693 $data = file_postupdate_standard_filemanager($data, 'files', $editoroptions, $this->_customdata->context, 'mod_assignment', 'response', $itemid);
2694 break;
2695 default :
2696 break;
2697 }
64f93798 2698 $data = file_postupdate_standard_editor($data, 'submissioncomment', $editoroptions, $this->_customdata->context, $editoroptions['component'], $editoroptions['filearea'], $itemid);
d2b6ee29 2699 }
18e6298c
MG
2700
2701 if ($this->use_advanced_grading() && !isset($data->advancedgrading)) {
2702 $data->advancedgrading = null;
2703 }
2704
d2b6ee29 2705 return $data;
2706 }
2707}
2708
b0f2597e 2709/// OTHER STANDARD FUNCTIONS ////////////////////////////////////////////////////////
2710
7af1e882 2711/**
2712 * Deletes an assignment instance
2713 *
2714 * This is done by calling the delete_instance() method of the assignment type class
2715 */
b0f2597e 2716function assignment_delete_instance($id){
c18269c7 2717 global $CFG, $DB;
26b90e70 2718
c18269c7 2719 if (! $assignment = $DB->get_record('assignment', array('id'=>$id))) {
b0f2597e 2720 return false;
26b90e70 2721 }
2722
1fc87774 2723 // fall back to base class if plugin missing
2724 $classfile = "$CFG->dirroot/mod/assignment/type/$assignment->assignmenttype/assignment.class.php";
2725 if (file_exists($classfile)) {
2726 require_once($classfile);
2727 $assignmentclass = "assignment_$assignment->assignmenttype";
2728
2729 } else {
2730 debugging("Missing assignment plug-in: {$assignment->assignmenttype}. Using base class for deleting instead.");
2731 $assignmentclass = "assignment_base";
2732 }
2733
b0f2597e 2734 $ass = new $assignmentclass();
2735 return $ass->delete_instance($assignment);
2736}
f466c9ed 2737
ac21ad39 2738
7af1e882 2739/**
2740 * Updates an assignment instance
2741 *
2742 * This is done by calling the update_instance() method of the assignment type class
2743 */
b0f2597e 2744function assignment_update_instance($assignment){
2745 global $CFG;
26b90e70 2746
aff24313 2747 $assignment->assignmenttype = clean_param($assignment->assignmenttype, PARAM_PLUGIN);
200c19fb 2748
b0f2597e 2749 require_once("$CFG->dirroot/mod/assignment/type/$assignment->assignmenttype/assignment.class.php");
2750 $assignmentclass = "assignment_$assignment->assignmenttype";
2751 $ass = new $assignmentclass();
2752 return $ass->update_instance($assignment);
45fa3412 2753}
26b90e70 2754
26b90e70 2755
7af1e882 2756/**
2757 * Adds an assignment instance
2758 *
2759 * This is done by calling the add_instance() method of the assignment type class
6b04fdc0
PS
2760 *
2761 * @param stdClass $assignment
2762 * @param mod_assignment_mod_form $mform
2763 * @return int intance id
7af1e882 2764 */
6b04fdc0 2765function assignment_add_instance($assignment, $mform = null) {
b0f2597e 2766 global $CFG;
f466c9ed 2767
aff24313 2768 $assignment->assignmenttype = clean_param($assignment->assignmenttype, PARAM_PLUGIN);
200c19fb 2769
b0f2597e 2770 require_once("$CFG->dirroot/mod/assignment/type/$assignment->assignmenttype/assignment.class.php");
2771 $assignmentclass = "assignment_$assignment->assignmenttype";
2772 $ass = new $assignmentclass();
2773 return $ass->add_instance($assignment);
2774}
f466c9ed 2775
73097f07 2776
7af1e882 2777/**
2778 * Returns an outline of a user interaction with an assignment
2779 *
2780 * This is done by calling the user_outline() method of the assignment type class
2781 */
73097f07 2782function assignment_user_outline($course, $user, $mod, $assignment) {
2783 global $CFG;
2784
1a96363a 2785 require_once("$CFG->libdir/gradelib.php");
73097f07 2786 require_once("$CFG->dirroot/mod/assignment/type/$assignment->assignmenttype/assignment.class.php");
2787 $assignmentclass = "assignment_$assignment->assignmenttype";
2788 $ass = new $assignmentclass($mod->id, $assignment, $mod, $course);
1a96363a
NC
2789 $grades = grade_get_grades($course->id, 'mod', 'assignment', $assignment->id, $user->id);
2790 if (!empty($grades->items[0]->grades)) {
2791 return $ass->user_outline(reset($grades->items[0]->grades));
2792 } else {
2793 return null;
2794 }
73097f07 2795}
2796
7af1e882 2797/**
2798 * Prints the complete info about a user's interaction with an assignment
2799 *
2800 * This is done by calling the user_complete() method of the assignment type class
2801 */
73097f07 2802function assignment_user_complete($course, $user, $mod, $assignment) {
2803 global $CFG;
2804
1a96363a 2805 require_once("$CFG->libdir/gradelib.php");
73097f07 2806 require_once("$CFG->dirroot/mod/assignment/type/$assignment->assignmenttype/assignment.class.php");
2807 $assignmentclass = "assignment_$assignment->assignmenttype";
2808 $ass = new $assignmentclass($mod->id, $assignment, $mod, $course);
1a96363a
NC
2809 $grades = grade_get_grades($course->id, 'mod', 'assignment', $assignment->id, $user->id);
2810 if (empty($grades->items[0]->grades)) {
2811 $grade = false;
2812 } else {
2813 $grade = reset($grades->items[0]->grades);
2814 }
2815 return $ass->user_complete($user, $grade);
73097f07 2816}
2817
7af1e882 2818/**
2819 * Function to be run periodically according to the moodle cron
2820 *
2821 * Finds all assignment notifications that have yet to be mailed out, and mails them
2822 */
73097f07 2823function assignment_cron () {
5053f00f 2824 global $CFG, $USER, $DB;
73097f07 2825
d014b69b 2826 /// first execute all crons in plugins
17da2e6f 2827 if ($plugins = get_plugin_list('assignment')) {
2828 foreach ($plugins as $plugin=>$dir) {
2829 require_once("$dir/assignment.class.php");
d014b69b 2830 $assignmentclass = "assignment_$plugin";
2831 $ass = new $assignmentclass();
2832 $ass->cron();
2833 }
2834 }
2835
73097f07 2836 /// Notices older than 1 day will not be mailed. This is to avoid the problem where
2837 /// cron has not been running for a long time, and then suddenly people are flooded
2838 /// with mail from the past few weeks or months
2839
2840 $timenow = time();
2841 $endtime = $timenow - $CFG->maxeditingtime;
2842 $starttime = $endtime - 24 * 3600; /// One day earlier
2843
2844 if ($submissions = assignment_get_unmailed_submissions($starttime, $endtime)) {
2845
98be6ed8 2846 $realuser = clone($USER);
2847
73097f07 2848 foreach ($submissions as $key => $submission) {
f685e830 2849 $DB->set_field("assignment_submissions", "mailed", "1", array("id"=>$submission->id));
73097f07 2850 }
2851
2852 $timenow = time();
2853
2854 foreach ($submissions as $submission) {
2855
2856 echo "Processing assignment submission $submission->id\n";
2857
5053f00f 2858 if (! $user = $DB->get_record("user", array("id"=>$submission->userid))) {
6b1564a8 2859 echo "Could not find user $user->id\n";
73097f07 2860 continue;
2861 }
2862
5053f00f 2863 if (! $course = $DB->get_record("course", array("id"=>$submission->course))) {
73097f07 2864 echo "Could not find course $submission->course\n";
2865 continue;
2866 }
98be6ed8 2867
2868 /// Override the language and timezone of the "current" user, so that
2869 /// mail is customised for the receiver.
e8b7114d 2870 cron_setup_user($user, $course);
98be6ed8 2871
01a67102 2872 $coursecontext = context_course::instance($submission->course);
8ebbb06a
SH
2873 $courseshortname = format_string($course->shortname, true, array('context' => $coursecontext));
2874 if (!is_enrolled($coursecontext, $user->id)) {
2875 echo fullname($user)." not an active participant in " . $courseshortname . "\n";
73097f07 2876 continue;
2877 }
2878
5053f00f 2879 if (! $teacher = $DB->get_record("user", array("id"=>$submission->teacher))) {
73097f07 2880 echo "Could not find teacher $submission->teacher\n";
2881 continue;
2882 }
2883
2884 if (! $mod = get_coursemodule_from_instance("assignment", $submission->assignment, $course->id)) {
2885 echo "Could not find course module for assignment id $submission->assignment\n";
2886 continue;
2887 }
2888
2889 if (! $mod->visible) { /// Hold mail notification for hidden assignments until later
2890 continue;
2891 }
2892
2893 $strassignments = get_string("modulenameplural", "assignment");
2894 $strassignment = get_string("modulename", "assignment");
2895
39790bd8 2896 $assignmentinfo = new stdClass();
73097f07 2897 $assignmentinfo->teacher = fullname($teacher);
2898 $assignmentinfo->assignment = format_string($submission->name,true);
2899 $assignmentinfo->url = "$CFG->wwwroot/mod/assignment/view.php?id=$mod->id";
2900
8ebbb06a
SH
2901 $postsubject = "$courseshortname: $strassignments: ".format_string($submission->name,true);
2902 $posttext = "$courseshortname -> $strassignments -> ".format_string($submission->name,true)."\n";
73097f07 2903 $posttext .= "---------------------------------------------------------------------\n";
3f19bff3 2904 $posttext .= get_string("assignmentmail", "assignment", $assignmentinfo)."\n";
73097f07 2905 $posttext .= "---------------------------------------------------------------------\n";
2906
2907 if ($user->mailformat == 1) { // HTML
2908 $posthtml = "<p><font face=\"sans-serif\">".
8ebbb06a 2909 "<a href=\"$CFG->wwwroot/course/view.php?id=$course->id\">$courseshortname</a> ->".
73097f07 2910 "<a href=\"$CFG->wwwroot/mod/assignment/index.php?id=$course->id\">$strassignments</a> ->".
2911 "<a href=\"$CFG->wwwroot/mod/assignment/view.php?id=$mod->id\">".format_string($submission->name,true)."</a></font></p>";
2912 $posthtml .= "<hr /><font face=\"sans-serif\">";
2913 $posthtml .= "<p>".get_string("assignmentmailhtml", "assignment", $assignmentinfo)."</p>";
2914 $posthtml .= "</font><hr />";
2915 } else {
2916 $posthtml = "";
2917 }
2918
39790bd8 2919 $eventdata = new stdClass();
3b120e46 2920 $eventdata->modulename = 'assignment';
2921 $eventdata->userfrom = $teacher;
2922 $eventdata->userto = $user;
2923 $eventdata->subject = $postsubject;
2924 $eventdata->fullmessage = $posttext;
2925 $eventdata->fullmessageformat = FORMAT_PLAIN;
2926 $eventdata->fullmessagehtml = $posthtml;
5daa7279 2927 $eventdata->smallmessage = get_string('assignmentmailsmall', 'assignment', $assignmentinfo);
d042ff06
AB
2928
2929 $eventdata->name = 'assignment_updates';
2930 $eventdata->component = 'mod_assignment';
2931 $eventdata->notification = 1;
0f1751b0
AD
2932 $eventdata->contexturl = $assignmentinfo->url;
2933 $eventdata->contexturlname = $assignmentinfo->assignment;
d042ff06 2934
7c7d3afa 2935 message_send($eventdata);
73097f07 2936 }
98be6ed8 2937
e8b7114d 2938 cron_setup_user();
73097f07 2939 }
2940
2941 return true;
2942}
2943
45fa3412 2944/**
2945 * Return grade for given user or all users.
2946 *
a153c9f2
AD
2947 * @param stdClass $assignment An assignment instance
2948 * @param int $userid Optional user id, 0 means all users
2949 * @return array An array of grades, false if none
45fa3412 2950 */
612607bd 2951function assignment_get_user_grades($assignment, $userid=0) {
5053f00f 2952 global $CFG, $DB;
45fa3412 2953
5053f00f 2954 if ($userid) {
2955 $user = "AND u.id = :userid";
2956 $params = array('userid'=>$userid);
2957 } else {
2958 $user = "";
2959 }
2960 $params['aid'] = $assignment->id;
45fa3412 2961
ced5ee59 2962 $sql = "SELECT u.id, u.id AS userid, s.grade AS rawgrade, s.submissioncomment AS feedback, s.format AS feedbackformat,
2963 s.teacher AS usermodified, s.timemarked AS dategraded, s.timemodified AS datesubmitted
5053f00f 2964 FROM {user} u, {assignment_submissions} s
2965 WHERE u.id = s.userid AND s.assignment = :aid
4a1be95c 2966 $user";
45fa3412 2967
5053f00f 2968 return $DB->get_records_sql($sql, $params);
45fa3412 2969}
2970
2971/**
775f811a 2972 * Update activity grades
45fa3412 2973 *
a153c9f2
AD
2974 * @category grade
2975 * @param stdClass $assignment Assignment instance
775f811a 2976 * @param int $userid specific user only, 0 means all
a153c9f2 2977 * @param bool $nullifnone Not used
45fa3412 2978 */
775f811a 2979function assignment_update_grades($assignment, $userid=0, $nullifnone=true) {
5053f00f 2980 global $CFG, $DB;
2981 require_once($CFG->libdir.'/gradelib.php');