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