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