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