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