Added a space before divs too
[moodle.git] / mod / assignment / lib.php
CommitLineData
5c6b657a 1<?PHP // $Id$
b0f2597e 2/**
3 * assignment_base is the base class for assignment types
4 *
5 * This class provides all the functionality for an assignment
6 */
04eba58f 7
1884f2a6 8DEFINE ('ASSIGNMENT_COUNT_WORDS', 1);
9DEFINE ('ASSIGNMENT_COUNT_LETTERS', 2);
d699cd1e 10
4909e176 11if (!isset($CFG->assignment_maxbytes)) {
12 set_config("assignment_maxbytes", 1024000); // Default maximum size for all assignments
04eba58f 13}
1884f2a6 14if (!isset($CFG->assignment_itemstocount)) {
15 set_config("assignment_itemstocount", ASSIGNMENT_COUNT_WORDS); // Default item to count
16}
04eba58f 17
7af1e882 18/**
b0f2597e 19 * Standard base class for all assignment submodules (assignment types).
b0f2597e 20 */
21class assignment_base {
22
23 var $cm;
24 var $course;
25 var $assignment;
7af1e882 26 var $strassignment;
27 var $strassignments;
28 var $strsubmissions;
29 var $strlastmodified;
30 var $navigation;
31 var $pagetitle;
32 var $currentgroup;
33 var $usehtmleditor;
34 var $defaultformat;
55b4d096 35 var $context;
34e67f76 36 var $lockedgrades;
b0f2597e 37
38 /**
39 * Constructor for the base assignment class
40 *
41 * Constructor for the base assignment class.
42 * If cmid is set create the cm, course, assignment objects.
7af1e882 43 * If the assignment is hidden and the user is not a teacher then
44 * this prints a page header and notice.
b0f2597e 45 *
46 * @param cmid integer, the current course module id - not set for new assignments
73097f07 47 * @param assignment object, usually null, but if we have it we pass it to save db access
7af1e882 48 * @param cm object, usually null, but if we have it we pass it to save db access
49 * @param course object, usually null, but if we have it we pass it to save db access
b0f2597e 50 */
7bddd4b7 51 function assignment_base($cmid='staticonly', $assignment=NULL, $cm=NULL, $course=NULL) {
52 if ($cmid == 'staticonly') {
53 //use static functions only!
54 return;
55 }
b0f2597e 56
57 global $CFG;
58
7bddd4b7 59 if ($cm) {
60 $this->cm = $cm;
61 } else if (! $this->cm = get_coursemodule_from_id('assignment', $cmid)) {
7bddd4b7 62 error('Course Module ID was incorrect');
63 }
04eba58f 64
7bddd4b7 65 $this->context = get_context_instance(CONTEXT_MODULE,$this->cm->id);
55b4d096 66
7bddd4b7 67 if ($course) {
68 $this->course = $course;
69 } else if (! $this->course = get_record('course', 'id', $this->cm->course)) {
70 error('Course is misconfigured');
71 }
04eba58f 72
7bddd4b7 73 if ($assignment) {
74 $this->assignment = $assignment;
75 } else if (! $this->assignment = get_record('assignment', 'id', $this->cm->instance)) {
76 error('assignment ID was incorrect');
77 }
78
b5ebd096 79 $this->assignment->cmidnumber = $this->cm->id; // compatibility with modedit assignment obj
80 $this->assignment->courseid = $this->course->id; // compatibility with modedit assignment obj
e6a4906b 81
34e67f76 82 require_once($CFG->libdir.'/gradelib.php');
83 $this->lockedgrades = grade_is_locked($this->course->id, 'mod', 'assignment', $this->assignment->id, 0);
84
7bddd4b7 85 $this->strassignment = get_string('modulename', 'assignment');
86 $this->strassignments = get_string('modulenameplural', 'assignment');
87 $this->strsubmissions = get_string('submissions', 'assignment');
88 $this->strlastmodified = get_string('lastmodified');
45fa3412 89
7bddd4b7 90 $this->navigation[] = array('name' => $this->strassignments, 'link' => "index.php?id={$this->course->id}", 'type' => 'activity');
45fa3412 91
7bddd4b7 92 $this->pagetitle = strip_tags($this->course->shortname.': '.$this->strassignment.': '.format_string($this->assignment->name,true));
93
94 // visibility
95 $context = get_context_instance(CONTEXT_MODULE, $cmid);
96 if (!$this->cm->visible and !has_capability('moodle/course:viewhiddenactivities', $context)) {
97 $pagetitle = strip_tags($this->course->shortname.': '.$this->strassignment);
98 $this->navigation[] = array('name' => $this->strassignment, 'link' => '', 'type' => 'activityinstance');
99 $navigation = build_navigation($this->navigation);
45fa3412 100
101 print_header($pagetitle, $this->course->fullname, "$this->navigation $this->strassignment",
7bddd4b7 102 "", "", true, '', navmenu($this->course, $this->cm));
103 notice(get_string("activityiscurrentlyhidden"), "$CFG->wwwroot/course/view.php?id={$this->course->id}");
73097f07 104 }
7bddd4b7 105 $this->currentgroup = get_and_set_current_group($this->course, groupmode($this->course, $this->cm));
e6a4906b 106
73097f07 107 /// Set up things for a HTML editor if it's needed
108 if ($this->usehtmleditor = can_use_html_editor()) {
109 $this->defaultformat = FORMAT_HTML;
110 } else {
111 $this->defaultformat = FORMAT_MOODLE;
e6a4906b 112 }
113 }
114
7af1e882 115 /**
116 * Display the assignment, used by view.php
117 *
118 * This in turn calls the methods producing individual parts of the page
b0f2597e 119 */
b0f2597e 120 function view() {
45fa3412 121
dabfd0ed 122 $context = get_context_instance(CONTEXT_MODULE,$this->cm->id);
0468976c 123 require_capability('mod/assignment:view', $context);
45fa3412 124
125 add_to_log($this->course->id, "assignment", "view", "view.php?id={$this->cm->id}",
b0f2597e 126 $this->assignment->id, $this->cm->id);
04eba58f 127
73097f07 128 $this->view_header();
04eba58f 129
f77cfb73 130 $this->view_intro();
04eba58f 131
f77cfb73 132 $this->view_dates();
04eba58f 133
b0f2597e 134 $this->view_feedback();
135
f77cfb73 136 $this->view_footer();
36eb856f 137 }
138
7af1e882 139 /**
140 * Display the header and top of a page
141 *
142 * (this doesn't change much for assignment types)
143 * This is used by the view() method to print the header of view.php but
144 * it can be used on other pages in which case the string to denote the
145 * page in the navigation trail should be passed as an argument
146 *
147 * @param $subpage string Description of subpage to be used in navigation trail
73097f07 148 */
149 function view_header($subpage='') {
150
151 global $CFG;
152
45fa3412 153
73097f07 154 if ($subpage) {
b9dc2734 155 $this->navigation[] = array('name' => format_string($this->assignment->name,true), 'link' => "view.php?id={$this->cm->id}", 'type' => 'activityinstance');
156 $this->navigation[] = array('name' => $subpage, 'link' => '', 'type' => 'title');
73097f07 157 } else {
b9dc2734 158 $this->navigation[] = array('name' => format_string($this->assignment->name,true), 'link' => '', 'type' => 'activityinstance');
73097f07 159 }
45fa3412 160
70c6c0ad 161 $navigation = build_navigation($this->navigation);
73097f07 162
45fa3412 163 print_header($this->pagetitle, $this->course->fullname, $navigation, '', '',
164 true, update_module_button($this->cm->id, $this->course->id, $this->strassignment),
73097f07 165 navmenu($this->course, $this->cm));
166
7bddd4b7 167 $groupmode = groupmode($this->course, $this->cm);
168 $currentgroup = setup_and_print_groups($this->course, $groupmode, 'view.php?id=' . $this->cm->id);
45fa3412 169
73097f07 170 echo '<div class="reportlink">'.$this->submittedlink().'</div>';
7bddd4b7 171 echo '<div class="clearer"></div>';
73097f07 172 }
173
174
7af1e882 175 /**
f77cfb73 176 * Display the assignment intro
7af1e882 177 *
178 * This will most likely be extended by assignment type plug-ins
179 * The default implementation prints the assignment description in a box
f77cfb73 180 */
181 function view_intro() {
32776fef 182 print_simple_box_start('center', '', '', 0, 'generalbox', 'intro');
1e4343a0 183 $formatoptions = new stdClass;
184 $formatoptions->noclean = true;
185 echo format_text($this->assignment->description, $this->assignment->format, $formatoptions);
f77cfb73 186 print_simple_box_end();
187 }
188
7af1e882 189 /**
f77cfb73 190 * Display the assignment dates
7af1e882 191 *
192 * Prints the assignment start and end dates in a box.
193 * This will be suitable for most assignment types
f77cfb73 194 */
195 function view_dates() {
196 if (!$this->assignment->timeavailable && !$this->assignment->timedue) {
197 return;
198 }
199
32776fef 200 print_simple_box_start('center', '', '', 0, 'generalbox', 'dates');
f77cfb73 201 echo '<table>';
202 if ($this->assignment->timeavailable) {
203 echo '<tr><td class="c0">'.get_string('availabledate','assignment').':</td>';
204 echo ' <td class="c1">'.userdate($this->assignment->timeavailable).'</td></tr>';
205 }
206 if ($this->assignment->timedue) {
207 echo '<tr><td class="c0">'.get_string('duedate','assignment').':</td>';
208 echo ' <td class="c1">'.userdate($this->assignment->timedue).'</td></tr>';
209 }
210 echo '</table>';
211 print_simple_box_end();
212 }
213
214
7af1e882 215 /**
216 * Display the bottom and footer of a page
217 *
218 * This default method just prints the footer.
219 * This will be suitable for most assignment types
73097f07 220 */
221 function view_footer() {
222 print_footer($this->course);
223 }
224
7af1e882 225 /**
226 * Display the feedback to the student
227 *
228 * This default method prints the teacher picture and name, date when marked,
ea6432fe 229 * grade and teacher submissioncomment.
7af1e882 230 *
231 * @param $submission object The submission object or NULL in which case it will be loaded
232 */
73097f07 233 function view_feedback($submission=NULL) {
b0f2597e 234 global $USER;
e6a4906b 235
73097f07 236 if (!$submission) { /// Get submission for this assignment
237 $submission = $this->get_submission($USER->id);
70b2c772 238 }
239
240 if (empty($submission->timemarked)) { /// Nothing to show, so print nothing
241 return;
9c48354d 242 }
e6a4906b 243
b0f2597e 244 /// We need the teacher info
245 if (! $teacher = get_record('user', 'id', $submission->teacher)) {
b0f2597e 246 error('Could not find the teacher');
247 }
e6a4906b 248
b0f2597e 249 /// Print the feedback
6d4ecaec 250 print_heading(get_string('feedbackfromteacher', 'assignment', $this->course->teacher));
251
b0f2597e 252 echo '<table cellspacing="0" class="feedback">';
253
254 echo '<tr>';
255 echo '<td class="left picture">';
256 print_user_picture($teacher->id, $this->course->id, $teacher->picture);
257 echo '</td>';
6d4ecaec 258 echo '<td class="topic">';
70b2c772 259 echo '<div class="from">';
73097f07 260 echo '<div class="fullname">'.fullname($teacher).'</div>';
6d4ecaec 261 echo '<div class="time">'.userdate($submission->timemarked).'</div>';
70b2c772 262 echo '</div>';
b0f2597e 263 echo '</td>';
264 echo '</tr>';
265
266 echo '<tr>';
267 echo '<td class="left side">&nbsp;</td>';
6d4ecaec 268 echo '<td class="content">';
b0f2597e 269 if ($this->assignment->grade) {
6d4ecaec 270 echo '<div class="grade">';
70b2c772 271 echo get_string("grade").': '.$this->display_grade($submission->grade);
6d4ecaec 272 echo '</div>';
52436fe1 273 echo '<div class="clearer"></div>';
e6a4906b 274 }
dcd338ff 275
6d4ecaec 276 echo '<div class="comment">';
ea6432fe 277 echo format_text($submission->submissioncomment, $submission->format);
6d4ecaec 278 echo '</div>';
b0f2597e 279 echo '</tr>';
280
281 echo '</table>';
e6a4906b 282 }
e6a4906b 283
45fa3412 284 /**
ba16713f 285 * Returns a link with info about the state of the assignment submissions
7af1e882 286 *
287 * This is used by view_header to put this link at the top right of the page.
288 * For teachers it gives the number of submitted assignments with a link
289 * For students it gives the time of their submission.
290 * This will be suitable for most assignment types.
291 * @return string
ba16713f 292 */
293 function submittedlink() {
294 global $USER;
295
296 $submitted = '';
297
bbbf2d40 298 $context = get_context_instance(CONTEXT_MODULE,$this->cm->id);
1648afb2 299 if (has_capability('mod/assignment:grade', $context)) {
bbbf2d40 300
301 // if this user can mark and is put in a group
302 // then he can only see/mark submission in his own groups
1648afb2 303 if (!has_capability('moodle/course:managegroups', $context) and (groupmode($this->course, $this->cm) == SEPARATEGROUPS)) {
bbbf2d40 304 $count = $this->count_real_submissions($this->currentgroup); // Only their groups
ba16713f 305 } else {
306 $count = $this->count_real_submissions(); // Everyone
307 }
308 $submitted = '<a href="submissions.php?id='.$this->cm->id.'">'.
309 get_string('viewsubmissions', 'assignment', $count).'</a>';
310 } else {
86a1ba04 311 if (!empty($USER->id)) {
ba16713f 312 if ($submission = $this->get_submission($USER->id)) {
313 if ($submission->timemodified) {
1e4343a0 314 if ($submission->timemodified <= $this->assignment->timedue || empty($this->assignment->timedue)) {
ba16713f 315 $submitted = '<span class="early">'.userdate($submission->timemodified).'</span>';
316 } else {
317 $submitted = '<span class="late">'.userdate($submission->timemodified).'</span>';
318 }
319 }
320 }
321 }
322 }
323
324 return $submitted;
325 }
326
327
436cfa9f 328 function setup_elements(&$mform) {
45fa3412 329
436cfa9f 330 }
331
7af1e882 332 /**
333 * Create a new assignment activity
334 *
335 * Given an object containing all the necessary data,
336 * (defined by the form in mod.html) this function
337 * will create a new instance and return the id number
338 * of the new instance.
339 * The due data is added to the calendar
340 * This is common to all assignment types.
341 *
342 * @param $assignment object The data from the form on mod.html
343 * @return int The id of the assignment
344 */
b0f2597e 345 function add_instance($assignment) {
7bddd4b7 346 global $COURSE;
b0f2597e 347
348 $assignment->timemodified = time();
7bddd4b7 349 $assignment->courseid = $assignment->course;
38147229 350
736f191c 351 if ($returnid = insert_record("assignment", $assignment)) {
7bddd4b7 352 $assignment->id = $returnid;
736f191c 353
1e4343a0 354 if ($assignment->timedue) {
7bddd4b7 355 $event = new object();
1e4343a0 356 $event->name = $assignment->name;
357 $event->description = $assignment->description;
358 $event->courseid = $assignment->course;
359 $event->groupid = 0;
360 $event->userid = 0;
361 $event->modulename = 'assignment';
362 $event->instance = $returnid;
363 $event->eventtype = 'due';
364 $event->timestart = $assignment->timedue;
365 $event->timeduration = 0;
736f191c 366
1e4343a0 367 add_event($event);
368 }
7bddd4b7 369
370 $assignment = stripslashes_recursive($assignment);
612607bd 371 assignment_grade_item_update($assignment);
7bddd4b7 372
736f191c 373 }
374
7bddd4b7 375
736f191c 376 return $returnid;
b0f2597e 377 }
d699cd1e 378
7af1e882 379 /**
380 * Deletes an assignment activity
381 *
1f8c6549 382 * Deletes all database records, files and calendar events for this assignment.
7af1e882 383 * @param $assignment object The assignment to be deleted
384 * @return boolean False indicates error
385 */
b0f2597e 386 function delete_instance($assignment) {
1f8c6549 387 global $CFG;
388
ada917d5 389 $assignment->courseid = $assignment->course;
390
736f191c 391 $result = true;
392
393 if (! delete_records('assignment_submissions', 'assignment', $assignment->id)) {
394 $result = false;
395 }
396
397 if (! delete_records('assignment', 'id', $assignment->id)) {
398 $result = false;
399 }
400
401 if (! delete_records('event', 'modulename', 'assignment', 'instance', $assignment->id)) {
402 $result = false;
403 }
45fa3412 404
1f8c6549 405 // delete file area with all attachments - ignore errors
406 require_once($CFG->libdir.'/filelib.php');
407 fulldelete($CFG->dataroot.'/'.$assignment->course.'/'.$CFG->moddata.'/assignment/'.$assignment->id);
408
45fa3412 409 assignment_grade_item_delete($assignment);
ada917d5 410
736f191c 411 return $result;
b0f2597e 412 }
d699cd1e 413
7af1e882 414 /**
415 * Updates a new assignment activity
416 *
417 * Given an object containing all the necessary data,
418 * (defined by the form in mod.html) this function
419 * will update the assignment instance and return the id number
420 * The due date is updated in the calendar
421 * This is common to all assignment types.
422 *
423 * @param $assignment object The data from the form on mod.html
424 * @return int The assignment id
425 */
b0f2597e 426 function update_instance($assignment) {
7bddd4b7 427 global $COURSE;
b0f2597e 428
38147229 429 $assignment->timemodified = time();
38147229 430
b0f2597e 431 $assignment->id = $assignment->instance;
7bddd4b7 432 $assignment->courseid = $assignment->course;
736f191c 433
7bddd4b7 434 if (!update_record('assignment', $assignment)) {
435 return false;
436 }
736f191c 437
7bddd4b7 438 if ($assignment->timedue) {
439 $event = new object();
736f191c 440
7bddd4b7 441 if ($event->id = get_field('event', 'id', 'modulename', 'assignment', 'instance', $assignment->id)) {
736f191c 442
7bddd4b7 443 $event->name = $assignment->name;
444 $event->description = $assignment->description;
445 $event->timestart = $assignment->timedue;
736f191c 446
7bddd4b7 447 update_event($event);
47263937 448 } else {
7bddd4b7 449 $event = new object();
450 $event->name = $assignment->name;
451 $event->description = $assignment->description;
452 $event->courseid = $assignment->course;
453 $event->groupid = 0;
454 $event->userid = 0;
455 $event->modulename = 'assignment';
456 $event->instance = $assignment->id;
457 $event->eventtype = 'due';
458 $event->timestart = $assignment->timedue;
459 $event->timeduration = 0;
460
461 add_event($event);
736f191c 462 }
7bddd4b7 463 } else {
464 delete_records('event', 'modulename', 'assignment', 'instance', $assignment->id);
736f191c 465 }
466
7bddd4b7 467 // get existing grade item
468 $assignment = stripslashes_recursive($assignment);
de420c11 469
45fa3412 470 assignment_grade_item_update($assignment);
7bddd4b7 471
472 return true;
473 }
474
475 /**
45fa3412 476 * Update grade item for this submission.
7bddd4b7 477 */
45fa3412 478 function update_grade($submission) {
612607bd 479 assignment_update_grades($this->assignment, $submission->userid);
b0f2597e 480 }
481
7af1e882 482 /**
b0f2597e 483 * Top-level function for handling of submissions called by submissions.php
7af1e882 484 *
485 * This is for handling the teacher interaction with the grading interface
486 * This should be suitable for most assignment types.
487 *
488 * @param $mode string Specifies the kind of teacher interaction taking place
b0f2597e 489 */
490 function submissions($mode) {
9bf660b3 491 ///The main switch is changed to facilitate
492 ///1) Batch fast grading
493 ///2) Skip to the next one on the popup
494 ///3) Save and Skip to the next one on the popup
45fa3412 495
9bf660b3 496 //make user global so we can use the id
497 global $USER;
45fa3412 498
34e67f76 499 // no grading when grades are locked
500 if ($this->lockedgrades) {
501 $mode = 'all';
502 }
503
b0f2597e 504 switch ($mode) {
505 case 'grade': // We are in a popup window grading
506 if ($submission = $this->process_feedback()) {
5a36be8c 507 //IE needs proper header with encoding
508 print_header(get_string('feedback', 'assignment').':'.format_string($this->assignment->name));
b0f2597e 509 print_heading(get_string('changessaved'));
73963212 510 print $this->update_main_listing($submission);
b0f2597e 511 }
989a0a52 512 close_window();
b0f2597e 513 break;
9cc9b7c1 514
b0f2597e 515 case 'single': // We are in a popup window displaying submission
516 $this->display_submission();
517 break;
a56d79cd 518
1648afb2 519 case 'all': // Main window, display everything
b0f2597e 520 $this->display_submissions();
521 break;
082215e6 522
9bf660b3 523 case 'fastgrade':
082215e6 524 ///do the fast grading stuff - this process should work for all 3 subclasses
39e11905 525 $grading = false;
16907e53 526 $commenting = false;
39e11905 527 $col = false;
ea6432fe 528 if (isset($_POST['submissioncomment'])) {
529 $col = 'submissioncomment';
16907e53 530 $commenting = true;
531 }
532 if (isset($_POST['menu'])) {
39e11905 533 $col = 'menu';
16907e53 534 $grading = true;
535 }
39e11905 536 if (!$col) {
ea6432fe 537 //both submissioncomment and grade columns collapsed..
45fa3412 538 $this->display_submissions();
16907e53 539 break;
540 }
39e11905 541 foreach ($_POST[$col] as $id => $unusedvalue){
77f4b17b 542
543 $id = (int)$id; //clean parameter name
cc03871b 544
545 $this->process_outcomes($id);
546
39e11905 547 if (!$submission = $this->get_submission($id)) {
548 $submission = $this->prepare_new_submission($id);
549 $newsubmission = true;
550 } else {
551 $newsubmission = false;
552 }
553 unset($submission->data1); // Don't need to update this.
554 unset($submission->data2); // Don't need to update this.
16907e53 555
9bf660b3 556 //for fast grade, we need to check if any changes take place
16907e53 557 $updatedb = false;
558
559 if ($grading) {
560 $grade = $_POST['menu'][$id];
39e11905 561 $updatedb = $updatedb || ($submission->grade != $grade);
562 $submission->grade = $grade;
16907e53 563 } else {
39e11905 564 if (!$newsubmission) {
565 unset($submission->grade); // Don't need to update this.
566 }
16907e53 567 }
568 if ($commenting) {
ea6432fe 569 $commentvalue = trim($_POST['submissioncomment'][$id]);
570 $updatedb = $updatedb || ($submission->submissioncomment != stripslashes($commentvalue));
571 $submission->submissioncomment = $commentvalue;
16907e53 572 } else {
ea6432fe 573 unset($submission->submissioncomment); // Don't need to update this.
9bf660b3 574 }
575
39e11905 576 $submission->teacher = $USER->id;
577 $submission->mailed = $updatedb?0:$submission->mailed;//only change if it's an update
578 $submission->timemarked = time();
579
580 //if it is not an update, we don't change the last modified time etc.
ea6432fe 581 //this will also not write into database if no submissioncomment and grade is entered.
39e11905 582
16907e53 583 if ($updatedb){
39e11905 584 if ($newsubmission) {
7bddd4b7 585 if (!$sid = insert_record('assignment_submissions', $submission)) {
39e11905 586 return false;
587 }
7bddd4b7 588 $submission->id = $sid;
39e11905 589 } else {
590 if (!update_record('assignment_submissions', $submission)) {
591 return false;
592 }
7bddd4b7 593 }
594
595 // triger grade event
45fa3412 596 $this->update_grade($submission);
7bddd4b7 597
39e11905 598 //add to log only if updating
45fa3412 599 add_to_log($this->course->id, 'assignment', 'update grades',
600 'submissions.php?id='.$this->assignment->id.'&user='.$submission->userid,
601 $submission->userid, $this->cm->id);
9bf660b3 602 }
45fa3412 603
604 }
cc03871b 605
e11dd872 606 print_heading(get_string('changessaved'));
45fa3412 607 $this->display_submissions();
9bf660b3 608 break;
39e11905 609
610
9bf660b3 611 case 'next':
612 /// We are currently in pop up, but we want to skip to next one without saving.
613 /// This turns out to be similar to a single case
614 /// The URL used is for the next submission.
45fa3412 615
9bf660b3 616 $this->display_submission();
617 break;
45fa3412 618
9bf660b3 619 case 'saveandnext':
620 ///We are in pop up. save the current one and go to the next one.
621 //first we save the current changes
622 if ($submission = $this->process_feedback()) {
623 //print_heading(get_string('changessaved'));
73963212 624 $extra_javascript = $this->update_main_listing($submission);
9bf660b3 625 }
45fa3412 626
9bf660b3 627 //then we display the next submission
73963212 628 $this->display_submission($extra_javascript);
9bf660b3 629 break;
45fa3412 630
9bf660b3 631 default:
632 echo "something seriously is wrong!!";
45fa3412 633 break;
a56d79cd 634 }
b0f2597e 635 }
45fa3412 636
7af1e882 637 /**
638 * Helper method updating the listing on the main script from popup using javascript
639 *
640 * @param $submission object The submission whose data is to be updated on the main page
641 */
be86672d 642 function update_main_listing($submission) {
643 global $SESSION;
45fa3412 644
73963212 645 $output = '';
646
9bf660b3 647 $perpage = get_user_preferences('assignment_perpage', 10);
be86672d 648
9bf660b3 649 $quickgrade = get_user_preferences('assignment_quickgrade', 0);
45fa3412 650
be86672d 651 /// Run some Javascript to try and update the parent page
73963212 652 $output .= '<script type="text/javascript">'."\n<!--\n";
ea6432fe 653 if (empty($SESSION->flextable['mod-assignment-submissions']->collapse['submissioncomment'])) {
9bf660b3 654 if ($quickgrade){
16fc2088 655 $output.= 'opener.document.getElementById("submissioncomment'.$submission->userid.'").value="'
ea6432fe 656 .trim($submission->submissioncomment).'";'."\n";
9bf660b3 657 } else {
73963212 658 $output.= 'opener.document.getElementById("com'.$submission->userid.
ea6432fe 659 '").innerHTML="'.shorten_text(trim(strip_tags($submission->submissioncomment)), 15)."\";\n";
9bf660b3 660 }
be86672d 661 }
9bf660b3 662
663 if (empty($SESSION->flextable['mod-assignment-submissions']->collapse['grade'])) {
664 //echo optional_param('menuindex');
665 if ($quickgrade){
16fc2088 666 $output.= 'opener.document.getElementById("menumenu'.$submission->userid.
667 '").selectedIndex="'.optional_param('menuindex', 0, PARAM_INT).'";'."\n";
9bf660b3 668 } else {
73963212 669 $output.= 'opener.document.getElementById("g'.$submission->userid.'").innerHTML="'.
9bf660b3 670 $this->display_grade($submission->grade)."\";\n";
45fa3412 671 }
672 }
9bf660b3 673 //need to add student's assignments in there too.
73097f07 674 if (empty($SESSION->flextable['mod-assignment-submissions']->collapse['timemodified']) &&
675 $submission->timemodified) {
73963212 676 $output.= 'opener.document.getElementById("ts'.$submission->userid.
3a935caf 677 '").innerHTML="'.addslashes_js($this->print_student_answer($submission->userid)).userdate($submission->timemodified)."\";\n";
be86672d 678 }
45fa3412 679
73097f07 680 if (empty($SESSION->flextable['mod-assignment-submissions']->collapse['timemarked']) &&
681 $submission->timemarked) {
73963212 682 $output.= 'opener.document.getElementById("tt'.$submission->userid.
be86672d 683 '").innerHTML="'.userdate($submission->timemarked)."\";\n";
684 }
45fa3412 685
be86672d 686 if (empty($SESSION->flextable['mod-assignment-submissions']->collapse['status'])) {
73963212 687 $output.= 'opener.document.getElementById("up'.$submission->userid.'").className="s1";';
9bf660b3 688 $buttontext = get_string('update');
45fa3412 689 $button = link_to_popup_window ('/mod/assignment/submissions.php?id='.$this->cm->id.'&amp;userid='.$submission->userid.'&amp;mode=single'.'&amp;offset='.(optional_param('offset', '', PARAM_INT)-1),
9bf660b3 690 'grade'.$submission->userid, $buttontext, 450, 700, $buttontext, 'none', true, 'button'.$submission->userid);
3a935caf 691 $output.= 'opener.document.getElementById("up'.$submission->userid.'").innerHTML="'.addslashes_js($button).'";';
45fa3412 692 }
cc03871b 693
694 if (empty($SESSION->flextable['mod-assignment-submissions']->collapse['outcomes'])) {
695 // TODO: add some javascript for updating of outcomes here
696 if ($outcomes_data = grade_get_outcomes($this->course->id, 'mod', 'assignment', $this->assignment->id, $submission->userid)) {
697 foreach($outcomes_data as $n=>$data) {
698 if ($data->locked) {
699 continue;
700 }
701
702 if ($quickgrade){
703 $output.= 'opener.document.getElementById("outcome_'.$n.'_'.$submission->userid.
704 '").selectedIndex="'.$data->grade.'";'."\n";
705 } else {
706 $options = make_grades_menu(-$data->scaleid);
707 $options[0] = get_string('nooutcome', 'grades');
708 $output.= 'opener.document.getElementById("outcome_'.$n.'_'.$submission->userid.'").innerHTML="'.$options[$data->grade]."\";\n";
709
710 }
711
712 }
713 }
714 }
715
73963212 716 $output .= "\n-->\n</script>";
717 return $output;
be86672d 718 }
d699cd1e 719
7af1e882 720 /**
721 * Return a grade in user-friendly form, whether it's a scale or not
45fa3412 722 *
7af1e882 723 * @param $grade
724 * @return string User-friendly representation of grade
d59269cf 725 */
726 function display_grade($grade) {
727
c86aa2a4 728 static $scalegrades = array(); // Cache scales for each assignment - they might have different scales!!
d59269cf 729
730 if ($this->assignment->grade >= 0) { // Normal number
082215e6 731 if ($grade == -1) {
732 return '-';
733 } else {
734 return $grade.' / '.$this->assignment->grade;
735 }
d59269cf 736
737 } else { // Scale
c86aa2a4 738 if (empty($scalegrades[$this->assignment->id])) {
d59269cf 739 if ($scale = get_record('scale', 'id', -($this->assignment->grade))) {
c86aa2a4 740 $scalegrades[$this->assignment->id] = make_menu_from_list($scale->scale);
d59269cf 741 } else {
742 return '-';
743 }
744 }
c86aa2a4 745 if (isset($scalegrades[$this->assignment->id][$grade])) {
746 return $scalegrades[$this->assignment->id][$grade];
0f7d4e5e 747 }
39e11905 748 return '-';
d59269cf 749 }
750 }
751
7af1e882 752 /**
b0f2597e 753 * Display a single submission, ready for grading on a popup window
7af1e882 754 *
ea6432fe 755 * This default method prints the teacher info and submissioncomment box at the top and
7af1e882 756 * the student info and submission at the bottom.
757 * This method also fetches the necessary data in order to be able to
758 * provide a "Next submission" button.
759 * Calls preprocess_submission() to give assignment type plug-ins a chance
760 * to process submissions before they are graded
761 * This method gets its arguments from the page parameters userid and offset
b0f2597e 762 */
73963212 763 function display_submission($extra_javascript = '') {
45fa3412 764
082215e6 765 global $CFG;
cc03871b 766 require_once($CFG->libdir.'/gradelib.php');
45fa3412 767
4fdabdc3 768 $userid = required_param('userid', PARAM_INT);
769 $offset = required_param('offset', PARAM_INT);//offset for where to start looking for student.
d699cd1e 770
b0f2597e 771 if (!$user = get_record('user', 'id', $userid)) {
772 error('No such user!');
773 }
d699cd1e 774
39e11905 775 if (!$submission = $this->get_submission($user->id)) {
776 $submission = $this->prepare_new_submission($userid);
b0f2597e 777 }
b0f2597e 778 if ($submission->timemodified > $submission->timemarked) {
779 $subtype = 'assignmentnew';
780 } else {
781 $subtype = 'assignmentold';
782 }
d699cd1e 783
0cfafdc7 784 /// construct SQL, using current offset to find the data of the next student
9bf660b3 785 $course = $this->course;
786 $assignment = $this->assignment;
787 $cm = $this->cm;
16fc2088 788 $context = get_context_instance(CONTEXT_MODULE, $cm->id);
d699cd1e 789
7bddd4b7 790 /// Get all ppl that can submit assignments
0cfafdc7 791
7bddd4b7 792 $currentgroup = get_and_set_current_group($course, groupmode($course, $cm));
0cfafdc7 793
7bddd4b7 794 $users = get_users_by_capability($context, 'mod/assignment:submit', 'u.id, u.id', '', '', '', $currentgroup, '', false);
5b48244f 795
f5ae7c49 796 $select = 'SELECT u.id, u.firstname, u.lastname, u.picture,
45fa3412 797 s.id AS submissionid, s.grade, s.submissioncomment,
9ad5c91f 798 s.timemodified, s.timemarked ';
9bf660b3 799 $sql = 'FROM '.$CFG->prefix.'user u '.
45fa3412 800 'LEFT JOIN '.$CFG->prefix.'assignment_submissions s ON u.id = s.userid
9ad5c91f 801 AND s.assignment = '.$this->assignment->id.' '.
082215e6 802 'WHERE u.id IN ('.implode(',', array_keys($users)).') ';
45fa3412 803
02828119 804 require_once($CFG->libdir.'/tablelib.php');
0cfafdc7 805
806 if ($sort = flexible_table::get_sql_sort('mod-assignment-submissions')) {
02828119 807 $sort = 'ORDER BY '.$sort.' ';
808 }
809
082215e6 810 $nextid = 0;
422770d8 811 if (($auser = get_records_sql($select.$sql.$sort, $offset+1, 1)) !== false) {
70ad6fdb 812 $nextuser = array_shift($auser);
9ad5c91f 813 /// Calculate user status
45fa3412 814 $nextuser->status = ($nextuser->timemarked > 0) && ($nextuser->timemarked >= $nextuser->timemodified);
70ad6fdb 815 $nextid = $nextuser->id;
9bf660b3 816 }
81532b92 817
9bf660b3 818 print_header(get_string('feedback', 'assignment').':'.fullname($user, true).':'.format_string($this->assignment->name));
d699cd1e 819
73963212 820 /// Print any extra javascript needed for saveandnext
821 echo $extra_javascript;
822
9bf660b3 823 ///SOme javascript to help with setting up >.>
45fa3412 824
c9977d05 825 echo '<script type="text/javascript">'."\n";
9bf660b3 826 echo 'function setNext(){'."\n";
16fc2088 827 echo 'document.getElementById(\'submitform\').mode.value=\'next\';'."\n";
828 echo 'document.getElementById(\'submitform\').userid.value="'.$nextid.'";'."\n";
9bf660b3 829 echo '}'."\n";
45fa3412 830
9bf660b3 831 echo 'function saveNext(){'."\n";
16fc2088 832 echo 'document.getElementById(\'submitform\').mode.value=\'saveandnext\';'."\n";
833 echo 'document.getElementById(\'submitform\').userid.value="'.$nextid.'";'."\n";
834 echo 'document.getElementById(\'submitform\').saveuserid.value="'.$userid.'";'."\n";
835 echo 'document.getElementById(\'submitform\').menuindex.value = document.getElementById(\'submitform\').grade.selectedIndex;'."\n";
9bf660b3 836 echo '}'."\n";
45fa3412 837
9bf660b3 838 echo '</script>'."\n";
52436fe1 839 echo '<table cellspacing="0" class="feedback '.$subtype.'" >';
d699cd1e 840
9bf660b3 841 ///Start of teacher info row
c69cb506 842
b0f2597e 843 echo '<tr>';
141a922c 844 echo '<td class="picture teacher">';
b0f2597e 845 if ($submission->teacher) {
846 $teacher = get_record('user', 'id', $submission->teacher);
847 } else {
848 global $USER;
849 $teacher = $USER;
850 }
851 print_user_picture($teacher->id, $this->course->id, $teacher->picture);
852 echo '</td>';
853 echo '<td class="content">';
b7dc2256 854 echo '<form id="submitform" action="submissions.php" method="post">';
d9cb14b8 855 echo '<fieldset class="invisiblefieldset">';
16fc2088 856 echo '<input type="hidden" name="offset" value="'.($offset+1).'" />';
c9977d05 857 echo '<input type="hidden" name="userid" value="'.$userid.'" />';
858 echo '<input type="hidden" name="id" value="'.$this->cm->id.'" />';
859 echo '<input type="hidden" name="mode" value="grade" />';
860 echo '<input type="hidden" name="menuindex" value="0" />';//selected menu index
45fa3412 861
9bf660b3 862 //new hidden field, initialized to -1.
c9977d05 863 echo '<input type="hidden" name="saveuserid" value="-1" />';
52436fe1 864 if ($submission->timemarked) {
865 echo '<div class="from">';
866 echo '<div class="fullname">'.fullname($teacher, true).'</div>';
867 echo '<div class="time">'.userdate($submission->timemarked).'</div>';
868 echo '</div>';
869 }
cc03871b 870 echo '<div class="grade"><label for="menugrade">'.get_string('grade').'</label>';
082215e6 871 choose_from_menu(make_grades_menu($this->assignment->grade), 'grade', $submission->grade, get_string('nograde'), '', -1);
52436fe1 872 echo '</div>';
cc03871b 873 echo '<div class="clearer"></div>';
3a5ae660 874
cc03871b 875 if ($outcomes_data = grade_get_outcomes($this->course->id, 'mod', 'assignment', $this->assignment->id, $userid)) {
3a5ae660 876 echo '<div class="outcomes">';
cc03871b 877 foreach($outcomes_data as $n=>$data) {
878 echo '<div class="outcome"><label for="menuoutcome_'.$n.'">'.format_string($data->name).'</label>';
3a5ae660 879 $options = make_grades_menu(-$data->scaleid);
880 if ($data->locked) {
cc03871b 881 $options[0] = get_string('nooutcome', 'grades');
3a5ae660 882 echo $options[$data->grade];
883 } else {
cc03871b 884 choose_from_menu($options, 'outcome_'.$n.'['.$userid.']', $data->grade, get_string('nooutcome', 'grades'), '', 0);
3a5ae660 885 }
cc03871b 886 echo '</div>';
3a5ae660 887 }
888 echo '</div>';
889 }
890
b0f2597e 891
01e2fdfe 892 $this->preprocess_submission($submission);
893
b0f2597e 894 echo '<br />';
ea6432fe 895 print_textarea($this->usehtmleditor, 14, 58, 0, 0, 'submissioncomment', $submission->submissioncomment, $this->course->id);
ff8f7015 896
45fa3412 897 if ($this->usehtmleditor) {
ff8f7015 898 echo '<input type="hidden" name="format" value="'.FORMAT_HTML.'" />';
899 } else {
2bf7e0b1 900 echo '<div class="format">';
ff8f7015 901 choose_from_menu(format_text_menu(), "format", $submission->format, "");
f77cfb73 902 helpbutton("textformat", get_string("helpformatting"));
903 echo '</div>';
ff8f7015 904 }
b0f2597e 905
9bf660b3 906 ///Print Buttons in Single View
141a922c 907 echo '<div class="buttons">';
16fc2088 908 echo '<input type="submit" name="submit" value="'.get_string('savechanges').'" onclick = "document.getElementById(\'submitform\').menuindex.value = document.getElementById(\'submitform\').grade.selectedIndex" />';
b0f2597e 909 echo '<input type="submit" name="cancel" value="'.get_string('cancel').'" />';
9bf660b3 910 //if there are more to be graded.
082215e6 911 if ($nextid) {
5b48244f 912 echo '<input type="submit" name="saveandnext" value="'.get_string('saveandnext').'" onclick="saveNext()" />';
913 echo '<input type="submit" name="next" value="'.get_string('next').'" onclick="setNext();" />';
9bf660b3 914 }
73097f07 915 echo '</div>';
d9cb14b8 916 echo '</fieldset>';
b0f2597e 917 echo '</form>';
55b4d096 918
919 $customfeedback = $this->custom_feedbackform($submission, true);
920 if (!empty($customfeedback)) {
45fa3412 921 echo $customfeedback;
55b4d096 922 }
923
73097f07 924 echo '</td></tr>';
45fa3412 925
9bf660b3 926 ///End of teacher info row, Start of student info row
927 echo '<tr>';
141a922c 928 echo '<td class="picture user">';
9bf660b3 929 print_user_picture($user->id, $this->course->id, $user->picture);
930 echo '</td>';
931 echo '<td class="topic">';
932 echo '<div class="from">';
933 echo '<div class="fullname">'.fullname($user, true).'</div>';
934 if ($submission->timemodified) {
935 echo '<div class="time">'.userdate($submission->timemodified).
936 $this->display_lateness($submission->timemodified).'</div>';
937 }
938 echo '</div>';
939 $this->print_user_files($user->id);
940 echo '</td>';
941 echo '</tr>';
45fa3412 942
9bf660b3 943 ///End of student info row
45fa3412 944
73097f07 945 echo '</table>';
946
73097f07 947 if ($this->usehtmleditor) {
948 use_html_editor();
949 }
950
b0f2597e 951 print_footer('none');
d699cd1e 952 }
953
7af1e882 954 /**
01e2fdfe 955 * Preprocess submission before grading
7af1e882 956 *
957 * Called by display_submission()
958 * The default type does nothing here.
959 * @param $submission object The submission object
01e2fdfe 960 */
961 function preprocess_submission(&$submission) {
962 }
d699cd1e 963
7af1e882 964 /**
b0f2597e 965 * Display all the submissions ready for grading
966 */
967 function display_submissions() {
9bf660b3 968 global $CFG, $db, $USER;
cc03871b 969 require_once($CFG->libdir.'/gradelib.php');
3446205d 970
9bf660b3 971 /* first we check to see if the form has just been submitted
972 * to request user_preference updates
973 */
45fa3412 974
9bf660b3 975 if (isset($_POST['updatepref'])){
16907e53 976 $perpage = optional_param('perpage', 10, PARAM_INT);
9bf660b3 977 $perpage = ($perpage <= 0) ? 10 : $perpage ;
978 set_user_preference('assignment_perpage', $perpage);
16907e53 979 set_user_preference('assignment_quickgrade', optional_param('quickgrade',0, PARAM_BOOL));
9bf660b3 980 }
1b5910c4 981
45fa3412 982 /* next we get perpage and quickgrade (allow quick grade) params
9bf660b3 983 * from database
984 */
985 $perpage = get_user_preferences('assignment_perpage', 10);
34e67f76 986
987 if ($this->lockedgrades) {
988 $quickgrade = 0;
989 } else {
990 $quickgrade = get_user_preferences('assignment_quickgrade', 0);
991 }
45fa3412 992
9bf660b3 993 $teacherattempts = true; /// Temporary measure
16907e53 994 $page = optional_param('page', 0, PARAM_INT);
b0f2597e 995 $strsaveallfeedback = get_string('saveallfeedback', 'assignment');
d0ac6bc2 996
b0f2597e 997 /// Some shortcuts to make the code read better
45fa3412 998
b0f2597e 999 $course = $this->course;
1000 $assignment = $this->assignment;
1001 $cm = $this->cm;
45fa3412 1002
9bf660b3 1003 $tabindex = 1; //tabindex for quick grading tabbing; Not working for dropdowns yet
91719320 1004
b0f2597e 1005 add_to_log($course->id, 'assignment', 'view submission', 'submissions.php?id='.$this->assignment->id, $this->assignment->id, $this->cm->id);
01e38388 1006
1007 $navlinks = array();
3b27b0fe 1008 $navlinks[] = array('name' => $this->strassignments, 'link' => "index.php?id=$course->id", 'type' => 'activity');
1009 $navlinks[] = array('name' => format_string($this->assignment->name,true), 'link' => "view.php?a={$this->assignment->id}", 'type' => 'activityinstance');
1010 $navlinks[] = array('name' => $this->strsubmissions, 'link' => '', 'type' => 'title');
1011 $navigation = build_navigation($navlinks);
45fa3412 1012
b9dc2734 1013 print_header_simple(format_string($this->assignment->name,true), "", $navigation, '', '', true, update_module_button($cm->id, $course->id, $this->strassignment), navmenu($course, $cm));
7bddd4b7 1014
2d7617c6 1015 $context = get_context_instance(CONTEXT_MODULE, $cm->id);
7bddd4b7 1016
1017 /// find out current groups mode
2d7617c6 1018 $groupmode = groupmode($course, $cm);
7bddd4b7 1019 $currentgroup = setup_and_print_groups($course, $groupmode, 'submissions.php?id=' . $this->cm->id);
1020
1021 /// Get all ppl that are allowed to submit assignments
1022 $users = get_users_by_capability($context, 'mod/assignment:submit', '', '', '', '', $currentgroup, '', false);
91719320 1023
cc03871b 1024 $tablecolumns = array('picture', 'fullname', 'grade', 'submissioncomment', 'timemodified', 'timemarked', 'status', '');
1025 $tableheaders = array('', get_string('fullname'), get_string('grade'), get_string('comment', 'assignment'), get_string('lastmodified').' ('.$course->student.')', get_string('lastmodified').' ('.$course->teacher.')', get_string('status'), get_string('outcomes', 'grades'));
91719320 1026
b0f2597e 1027 require_once($CFG->libdir.'/tablelib.php');
1028 $table = new flexible_table('mod-assignment-submissions');
45fa3412 1029
b0f2597e 1030 $table->define_columns($tablecolumns);
1031 $table->define_headers($tableheaders);
fa22fd5f 1032 $table->define_baseurl($CFG->wwwroot.'/mod/assignment/submissions.php?id='.$this->cm->id.'&amp;currentgroup='.$currentgroup);
45fa3412 1033
246444b9 1034 $table->sortable(true, 'lastname');//sorted by lastname by default
b0f2597e 1035 $table->collapsible(true);
1036 $table->initialbars(true);
45fa3412 1037
b0f2597e 1038 $table->column_suppress('picture');
1039 $table->column_suppress('fullname');
45fa3412 1040
b0f2597e 1041 $table->column_class('picture', 'picture');
9437c854 1042 $table->column_class('fullname', 'fullname');
1043 $table->column_class('grade', 'grade');
ea6432fe 1044 $table->column_class('submissioncomment', 'comment');
9437c854 1045 $table->column_class('timemodified', 'timemodified');
1046 $table->column_class('timemarked', 'timemarked');
1047 $table->column_class('status', 'status');
cc03871b 1048 $table->column_class('outcomes', 'outcomes');
45fa3412 1049
b0f2597e 1050 $table->set_attribute('cellspacing', '0');
1051 $table->set_attribute('id', 'attempts');
9437c854 1052 $table->set_attribute('class', 'submissions');
b0f2597e 1053 $table->set_attribute('width', '90%');
d9cb14b8 1054 //$table->set_attribute('align', 'center');
45fa3412 1055
b0f2597e 1056 // Start working -- this is necessary as soon as the niceties are over
1057 $table->setup();
1058
b0f2597e 1059 /// Check to see if groups are being used in this assignment
05855091 1060
b0f2597e 1061 if (!$teacherattempts) {
1062 $teachers = get_course_teachers($course->id);
1063 if (!empty($teachers)) {
1064 $keys = array_keys($teachers);
1065 }
1066 foreach ($keys as $key) {
1067 unset($users[$key]);
1068 }
1069 }
45fa3412 1070
b0f2597e 1071 if (empty($users)) {
c8dbfa5c 1072 print_heading(get_string('noattempts','assignment'));
b0f2597e 1073 return true;
1074 }
0f1a97c2 1075
b0f2597e 1076 /// Construct the SQL
0f1a97c2 1077
b0f2597e 1078 if ($where = $table->get_sql_where()) {
b0f2597e 1079 $where .= ' AND ';
1080 }
0f1a97c2 1081
b0f2597e 1082 if ($sort = $table->get_sql_sort()) {
86f65395 1083 $sort = ' ORDER BY '.$sort;
b0f2597e 1084 }
9fa49e22 1085
45fa3412 1086 $select = 'SELECT u.id, u.firstname, u.lastname, u.picture,
1087 s.id AS submissionid, s.grade, s.submissioncomment,
9ad5c91f 1088 s.timemodified, s.timemarked ';
b0f2597e 1089 $sql = 'FROM '.$CFG->prefix.'user u '.
45fa3412 1090 'LEFT JOIN '.$CFG->prefix.'assignment_submissions s ON u.id = s.userid
9ad5c91f 1091 AND s.assignment = '.$this->assignment->id.' '.
306dc7e5 1092 'WHERE '.$where.'u.id IN ('.implode(',', array_keys($users)).') ';
45fa3412 1093
c5d36203 1094 $table->pagesize($perpage, count($users));
45fa3412 1095
9bf660b3 1096 ///offset used to calculate index of student in that particular query, needed for the pop up to know who's next
1097 $offset = $page * $perpage;
45fa3412 1098
b0f2597e 1099 $strupdate = get_string('update');
9437c854 1100 $strgrade = get_string('grade');
b0f2597e 1101 $grademenu = make_grades_menu($this->assignment->grade);
1102
422770d8 1103 if (($ausers = get_records_sql($select.$sql.$sort, $table->get_page_start(), $table->get_page_size())) !== false) {
45fa3412 1104
d59269cf 1105 foreach ($ausers as $auser) {
9ad5c91f 1106 /// Calculate user status
1107 $auser->status = ($auser->timemarked > 0) && ($auser->timemarked >= $auser->timemodified);
d59269cf 1108 $picture = print_user_picture($auser->id, $course->id, $auser->picture, false, true);
45fa3412 1109
39e11905 1110 if (empty($auser->submissionid)) {
1111 $auser->grade = -1; //no submission yet
9bf660b3 1112 }
45fa3412 1113
d59269cf 1114 if (!empty($auser->submissionid)) {
9bf660b3 1115 ///Prints student answer and student modified date
1116 ///attach file or print link to student answer, depending on the type of the assignment.
45fa3412 1117 ///Refer to print_student_answer in inherited classes.
1118 if ($auser->timemodified > 0) {
9bf660b3 1119 $studentmodified = '<div id="ts'.$auser->id.'">'.$this->print_student_answer($auser->id).userdate($auser->timemodified).'</div>';
d59269cf 1120 } else {
9437c854 1121 $studentmodified = '<div id="ts'.$auser->id.'">&nbsp;</div>';
d59269cf 1122 }
9bf660b3 1123 ///Print grade, dropdown or text
d59269cf 1124 if ($auser->timemarked > 0) {
1125 $teachermodified = '<div id="tt'.$auser->id.'">'.userdate($auser->timemarked).'</div>';
45fa3412 1126
9bf660b3 1127 if ($quickgrade) {
45fa3412 1128 $grade = '<div id="g'.$auser->id.'">'.choose_from_menu(make_grades_menu($this->assignment->grade),
082215e6 1129 'menu['.$auser->id.']', $auser->grade, get_string('nograde'),'',-1,true,false,$tabindex++).'</div>';
9bf660b3 1130 } else {
1131 $grade = '<div id="g'.$auser->id.'">'.$this->display_grade($auser->grade).'</div>';
1132 }
1133
b0f2597e 1134 } else {
9437c854 1135 $teachermodified = '<div id="tt'.$auser->id.'">&nbsp;</div>';
45fa3412 1136 if ($quickgrade){
1137 $grade = '<div id="g'.$auser->id.'">'.choose_from_menu(make_grades_menu($this->assignment->grade),
082215e6 1138 'menu['.$auser->id.']', $auser->grade, get_string('nograde'),'',-1,true,false,$tabindex++).'</div>';
9bf660b3 1139 } else {
1140 $grade = '<div id="g'.$auser->id.'">'.$this->display_grade($auser->grade).'</div>';
1141 }
1142 }
1143 ///Print Comment
1144 if ($quickgrade){
a1c91f9a 1145 $comment = '<div id="com'.$auser->id.'"><textarea tabindex="'.$tabindex++.'" name="submissioncomment['.$auser->id.']" id="submissioncomment'.$auser->id.'" rows="2" cols="20">'.($auser->submissioncomment).'</textarea></div>';
9bf660b3 1146 } else {
ea6432fe 1147 $comment = '<div id="com'.$auser->id.'">'.shorten_text(strip_tags($auser->submissioncomment),15).'</div>';
b0f2597e 1148 }
1149 } else {
9437c854 1150 $studentmodified = '<div id="ts'.$auser->id.'">&nbsp;</div>';
1151 $teachermodified = '<div id="tt'.$auser->id.'">&nbsp;</div>';
9bf660b3 1152 $status = '<div id="st'.$auser->id.'">&nbsp;</div>';
1153 if ($quickgrade){ // allow editing
45fa3412 1154 $grade = '<div id="g'.$auser->id.'">'.choose_from_menu(make_grades_menu($this->assignment->grade),
082215e6 1155 'menu['.$auser->id.']', $auser->grade, get_string('nograde'),'',-1,true,false,$tabindex++).'</div>';
9bf660b3 1156 } else {
39e11905 1157 $grade = '<div id="g'.$auser->id.'">-</div>';
9bf660b3 1158 }
1159 if ($quickgrade){
a1c91f9a 1160 $comment = '<div id="com'.$auser->id.'"><textarea tabindex="'.$tabindex++.'" name="submissioncomment['.$auser->id.']" id="submissioncomment'.$auser->id.'" rows="2" cols="20">'.($auser->submissioncomment).'</textarea></div>';
9bf660b3 1161 } else {
1162 $comment = '<div id="com'.$auser->id.'">&nbsp;</div>';
1163 }
b0f2597e 1164 }
9fa49e22 1165
9ad5c91f 1166 if (empty($auser->status)) { /// Confirm we have exclusively 0 or 1
0f7d4e5e 1167 $auser->status = 0;
9ad5c91f 1168 } else {
1169 $auser->status = 1;
0f7d4e5e 1170 }
1171
9437c854 1172 $buttontext = ($auser->status == 1) ? $strupdate : $strgrade;
45fa3412 1173
34e67f76 1174 if ($this->lockedgrades) {
1175 $status = get_string('gradeitemlocked', 'grades');
1176 } else {
1177 ///No more buttons, we use popups ;-).
1178 $button = link_to_popup_window ('/mod/assignment/submissions.php?id='.$this->cm->id.'&amp;userid='.$auser->id.'&amp;mode=single'.'&amp;offset='.$offset++,
cc03871b 1179 'grade'.$auser->id, $buttontext, 600, 780, $buttontext, 'none', true, 'button'.$auser->id);
34e67f76 1180
1181 $status = '<div id="up'.$auser->id.'" class="s'.$auser->status.'">'.$button.'</div>';
1182 }
cc03871b 1183
1184 $outcomes = '';
1185 if ($outcomes_data = grade_get_outcomes($this->course->id, 'mod', 'assignment', $this->assignment->id, $auser->id)) {
1186 foreach($outcomes_data as $n=>$data) {
1187 $outcomes .= '<div class="outcome"><label for="outcome_'.$n.'['.$auser->id.']">'.format_string($data->name).'</label>';
1188 $options = make_grades_menu(-$data->scaleid);
1189 if ($data->locked or !$quickgrade) {
1190 $options[0] = get_string('nooutcome', 'grades');
1191 $outcomes .= ':<span id="outcome_'.$n.'_'.$auser->id.'">'.$options[$data->grade].'</span>';
1192 } else {
1193 $outcomes .= choose_from_menu($options, 'outcome_'.$n.'['.$auser->id.']', $data->grade, get_string('nooutcome', 'grades'), '', 0, true, false, 0, 'outcome_'.$n.'_'.$auser->id);
1194 }
1195 echo '</div>';
1196 }
1197 }
1198
1199
1200 $row = array($picture, fullname($auser), $grade, $comment, $studentmodified, $teachermodified, $status, $outcomes);
d59269cf 1201 $table->add_data($row);
1202 }
b0f2597e 1203 }
45fa3412 1204
082215e6 1205 /// Print quickgrade form around the table
1206 if ($quickgrade){
b7dc2256 1207 echo '<form action="submissions.php" id="fastg" method="post">';
a1b5dd2b 1208 echo '<div>';
820aff13 1209 echo '<input type="hidden" name="id" value="'.$this->cm->id.'" />';
1210 echo '<input type="hidden" name="mode" value="fastgrade" />';
1211 echo '<input type="hidden" name="page" value="'.$page.'" />';
a1b5dd2b 1212 echo '</div>';
d9cb14b8 1213 echo '<div style="text-align:center"><input type="submit" name="fastg" value="'.get_string('saveallfeedback', 'assignment').'" /></div>';
082215e6 1214 }
1215
1216 $table->print_html(); /// Print the whole table
1217
9bf660b3 1218 if ($quickgrade){
d9cb14b8 1219 echo '<div style="text-align:center"><input type="submit" name="fastg" value="'.get_string('saveallfeedback', 'assignment').'" /></div>';
082215e6 1220 echo '</form>';
9bf660b3 1221 }
082215e6 1222 /// End of fast grading form
45fa3412 1223
082215e6 1224 /// Mini form for setting user preference
9bf660b3 1225 echo '<br />';
b7dc2256 1226 echo '<form id="options" action="submissions.php?id='.$this->cm->id.'" method="post">';
d9cb14b8 1227 echo '<fieldset class="invisiblefieldset">';
c9977d05 1228 echo '<input type="hidden" id="updatepref" name="updatepref" value="1" />';
d9cb14b8 1229 echo '<table id="optiontable">';
9bf660b3 1230 echo '<tr align="right"><td>';
1231 echo '<label for="perpage">'.get_string('pagesize','assignment').'</label>';
1232 echo ':</td>';
9bf660b3 1233 echo '<td align="left">';
1234 echo '<input type="text" id="perpage" name="perpage" size="1" value="'.$perpage.'" />';
1235 helpbutton('pagesize', get_string('pagesize','assignment'), 'assignment');
1236 echo '</td></tr>';
34e67f76 1237 if (!$this->lockedgrades) {
1238 echo '<tr align="right">';
1239 echo '<td>';
1240 print_string('quickgrade','assignment');
1241 echo ':</td>';
1242 echo '<td align="left">';
1243 if ($quickgrade){
1244 echo '<input type="checkbox" name="quickgrade" value="1" checked="checked" />';
1245 } else {
1246 echo '<input type="checkbox" name="quickgrade" value="1" />';
1247 }
1248 helpbutton('quickgrade', get_string('quickgrade', 'assignment'), 'assignment').'</p></div>';
1249 echo '</td></tr>';
9bf660b3 1250 }
9bf660b3 1251 echo '<tr>';
1252 echo '<td colspan="2" align="right">';
1253 echo '<input type="submit" value="'.get_string('savepreferences').'" />';
1254 echo '</td></tr></table>';
d9cb14b8 1255 echo '</fieldset>';
9bf660b3 1256 echo '</form>';
1257 ///End of mini form
b0f2597e 1258 print_footer($this->course);
8e340cb0 1259 }
d699cd1e 1260
7af1e882 1261 /**
1262 * Process teacher feedback submission
1263 *
1264 * This is called by submissions() when a grading even has taken place.
1265 * It gets its data from the submitted form.
1266 * @return object The updated submission object
b0f2597e 1267 */
1268 function process_feedback() {
d699cd1e 1269
b0f2597e 1270 global $USER;
d699cd1e 1271
9894b824 1272 if (!$feedback = data_submitted()) { // No incoming data?
b0f2597e 1273 return false;
d699cd1e 1274 }
b7b42874 1275
9bf660b3 1276 ///For save and next, we need to know the userid to save, and the userid to go
1277 ///We use a new hidden field in the form, and set it to -1. If it's set, we use this
1278 ///as the userid to store
1279 if ((int)$feedback->saveuserid !== -1){
1280 $feedback->userid = $feedback->saveuserid;
1281 }
1282
b0f2597e 1283 if (!empty($feedback->cancel)) { // User hit cancel button
1284 return false;
1285 }
d699cd1e 1286
cc03871b 1287 // store outcomes if needed
1288 $this->process_outcomes($feedback->userid);
1289
7af1e882 1290 $submission = $this->get_submission($feedback->userid, true); // Get or make one
d699cd1e 1291
7af1e882 1292 $submission->grade = $feedback->grade;
ea6432fe 1293 $submission->submissioncomment = $feedback->submissioncomment;
7af1e882 1294 $submission->format = $feedback->format;
1295 $submission->teacher = $USER->id;
1296 $submission->mailed = 0; // Make sure mail goes out (again, even)
1297 $submission->timemarked = time();
d699cd1e 1298
7af1e882 1299 unset($submission->data1); // Don't need to update this.
1300 unset($submission->data2); // Don't need to update this.
d4156e80 1301
b0f2597e 1302 if (empty($submission->timemodified)) { // eg for offline assignments
16fc2088 1303 // $submission->timemodified = time();
b0f2597e 1304 }
d699cd1e 1305
7af1e882 1306 if (! update_record('assignment_submissions', $submission)) {
b0f2597e 1307 return false;
1308 }
d699cd1e 1309
7bddd4b7 1310 // triger grade event
45fa3412 1311 $this->update_grade($submission);
7bddd4b7 1312
45fa3412 1313 add_to_log($this->course->id, 'assignment', 'update grades',
b0f2597e 1314 'submissions.php?id='.$this->assignment->id.'&user='.$feedback->userid, $feedback->userid, $this->cm->id);
45fa3412 1315
7af1e882 1316 return $submission;
d699cd1e 1317
d699cd1e 1318 }
d699cd1e 1319
cc03871b 1320 function process_outcomes($userid) {
1321 global $CFG, $USER;
1322 require_once($CFG->libdir.'/gradelib.php');
1323
1324 if (!$formdata = data_submitted()) {
1325 return;
1326 }
1327
1328 $data = array();
1329 if ($outcomes = grade_get_outcomes($this->course->id, 'mod', 'assignment', $this->assignment->id, $userid)) {
1330 foreach($outcomes as $n=>$old) {
1331 $name = 'outcome_'.$n;
1332 if (isset($formdata->{$name}[$userid]) and $old->grade != $formdata->{$name}[$userid]) {
1333 $data[$n] = $formdata->{$name}[$userid];
1334 }
1335 }
1336 }
1337 if (count($data) > 0) {
1338 grade_update_outcomes('mod/assignment', $this->course->id, 'mod', 'assignment', $this->assignment->id, $userid, $data);
1339 }
1340
1341 }
1342
7af1e882 1343 /**
1344 * Load the submission object for a particular user
1345 *
1346 * @param $userid int The id of the user whose submission we want or 0 in which case USER->id is used
1347 * @param $createnew boolean optional Defaults to false. If set to true a new submission object will be created in the database
1348 * @return object The submission
1349 */
f77cfb73 1350 function get_submission($userid=0, $createnew=false) {
1351 global $USER;
1352
1353 if (empty($userid)) {
1354 $userid = $USER->id;
1355 }
1356
b0f2597e 1357 $submission = get_record('assignment_submissions', 'assignment', $this->assignment->id, 'userid', $userid);
d699cd1e 1358
b0f2597e 1359 if ($submission || !$createnew) {
1360 return $submission;
1361 }
39e11905 1362 $newsubmission = $this->prepare_new_submission($userid);
b0f2597e 1363 if (!insert_record("assignment_submissions", $newsubmission)) {
1364 error("Could not insert a new empty submission");
1365 }
d699cd1e 1366
b0f2597e 1367 return get_record('assignment_submissions', 'assignment', $this->assignment->id, 'userid', $userid);
1368 }
d699cd1e 1369
7af1e882 1370 /**
1371 * Instantiates a new submission object for a given user
1372 *
1373 * Sets the assignment, userid and times, everything else is set to default values.
1374 * @param $userid int The userid for which we want a submission object
1375 * @return object The submission
1376 */
39e11905 1377 function prepare_new_submission($userid) {
45fa3412 1378 $submission = new Object;
39e11905 1379 $submission->assignment = $this->assignment->id;
1380 $submission->userid = $userid;
45fa3412 1381 //$submission->timecreated = time();
16fc2088 1382 $submission->timecreated = '';
1383 // teachers should not be modifying modified date, except offline assignments
39e11905 1384 $submission->timemodified = $submission->timecreated;
1385 $submission->numfiles = 0;
1386 $submission->data1 = '';
1387 $submission->data2 = '';
1388 $submission->grade = -1;
ea6432fe 1389 $submission->submissioncomment = '';
39e11905 1390 $submission->format = 0;
1391 $submission->teacher = 0;
1392 $submission->timemarked = 0;
1393 $submission->mailed = 0;
1394 return $submission;
1395 }
1396
7af1e882 1397 /**
1398 * Return all assignment submissions by ENROLLED students (even empty)
1399 *
1400 * @param $sort string optional field names for the ORDER BY in the sql query
1401 * @param $dir string optional specifying the sort direction, defaults to DESC
1402 * @return array The submission objects indexed by id
1403 */
b0f2597e 1404 function get_submissions($sort='', $dir='DESC') {
7af1e882 1405 return assignment_get_all_submissions($this->assignment, $sort, $dir);
b0f2597e 1406 }
1407
7af1e882 1408 /**
1409 * Counts all real assignment submissions by ENROLLED students (not empty ones)
1410 *
1411 * @param $groupid int optional If nonzero then count is restricted to this group
1412 * @return int The number of submissions
1413 */
b0f2597e 1414 function count_real_submissions($groupid=0) {
7af1e882 1415 return assignment_count_real_submissions($this->assignment, $groupid);
d59269cf 1416 }
d699cd1e 1417
7af1e882 1418 /**
1419 * Alerts teachers by email of new or changed assignments that need grading
1420 *
1421 * First checks whether the option to email teachers is set for this assignment.
1422 * Sends an email to ALL teachers in the course (or in the group if using separate groups).
1423 * Uses the methods email_teachers_text() and email_teachers_html() to construct the content.
1424 * @param $submission object The submission that has changed
1425 */
73097f07 1426 function email_teachers($submission) {
73097f07 1427 global $CFG;
1428
d8199f1d 1429 if (empty($this->assignment->emailteachers)) { // No need to do anything
73097f07 1430 return;
1431 }
1432
1433 $user = get_record('user', 'id', $submission->userid);
1434
413efd22 1435 if ($teachers = $this->get_graders($user)) {
73097f07 1436
1437 $strassignments = get_string('modulenameplural', 'assignment');
1438 $strassignment = get_string('modulename', 'assignment');
1439 $strsubmitted = get_string('submitted', 'assignment');
1440
1441 foreach ($teachers as $teacher) {
98be6ed8 1442 $info = new object();
413efd22 1443 $info->username = fullname($user, true);
d8199f1d 1444 $info->assignment = format_string($this->assignment->name,true);
1445 $info->url = $CFG->wwwroot.'/mod/assignment/submissions.php?id='.$this->cm->id;
1446
1447 $postsubject = $strsubmitted.': '.$info->username.' -> '.$this->assignment->name;
1448 $posttext = $this->email_teachers_text($info);
1449 $posthtml = ($teacher->mailformat == 1) ? $this->email_teachers_html($info) : '';
73097f07 1450
1451 @email_to_user($teacher, $user, $postsubject, $posttext, $posthtml); // If it fails, oh well, too bad.
1452 }
1453 }
1454 }
1455
413efd22 1456 /**
1457 * Returns a list of teachers that should be grading given submission
1458 */
1459 function get_graders($user) {
1460 //potential graders
7bddd4b7 1461 $potgraders = get_users_by_capability($this->context, 'mod/assignment:grade', '', '', '', '', '', '', false, false);
1462
413efd22 1463 $graders = array();
1464 if (groupmode($this->course, $this->cm) == SEPARATEGROUPS) { // Separate groups are being used
1465 if ($groups = user_group($this->course->id, $user->id)) { // Try to find all groups
1466 foreach ($groups as $group) {
1467 foreach ($potgraders as $t) {
1468 if ($t->id == $user->id) {
1469 continue; // do not send self
1470 }
1471 if (groups_is_member($group->id, $t->id)) {
1472 $graders[$t->id] = $t;
1473 }
1474 }
1475 }
1476 } else {
1477 // user not in group, try to find graders without group
1478 foreach ($potgraders as $t) {
1479 if ($t->id == $user->id) {
1480 continue; // do not send self
1481 }
1482 if (!user_group($this->course->id, $t->id)) { //ugly hack
1483 $graders[$t->id] = $t;
1484 }
1485 }
1486 }
1487 } else {
1488 foreach ($potgraders as $t) {
1489 if ($t->id == $user->id) {
1490 continue; // do not send self
1491 }
1492 $graders[$t->id] = $t;
1493 }
1494 }
1495 return $graders;
1496 }
1497
7af1e882 1498 /**
1499 * Creates the text content for emails to teachers
1500 *
1501 * @param $info object The info used by the 'emailteachermail' language string
1502 * @return string
1503 */
d8199f1d 1504 function email_teachers_text($info) {
413efd22 1505 $posttext = format_string($this->course->shortname).' -> '.$this->strassignments.' -> '.
1506 format_string($this->assignment->name)."\n";
d8199f1d 1507 $posttext .= '---------------------------------------------------------------------'."\n";
1508 $posttext .= get_string("emailteachermail", "assignment", $info)."\n";
73963212 1509 $posttext .= "\n---------------------------------------------------------------------\n";
d8199f1d 1510 return $posttext;
1511 }
1512
7af1e882 1513 /**
1514 * Creates the html content for emails to teachers
1515 *
1516 * @param $info object The info used by the 'emailteachermailhtml' language string
1517 * @return string
1518 */
d8199f1d 1519 function email_teachers_html($info) {
3554b5c2 1520 global $CFG;
d8199f1d 1521 $posthtml = '<p><font face="sans-serif">'.
413efd22 1522 '<a href="'.$CFG->wwwroot.'/course/view.php?id='.$this->course->id.'">'.format_string($this->course->shortname).'</a> ->'.
d8199f1d 1523 '<a href="'.$CFG->wwwroot.'/mod/assignment/index.php?id='.$this->course->id.'">'.$this->strassignments.'</a> ->'.
413efd22 1524 '<a href="'.$CFG->wwwroot.'/mod/assignment/view.php?id='.$this->cm->id.'">'.format_string($this->assignment->name).'</a></font></p>';
d8199f1d 1525 $posthtml .= '<hr /><font face="sans-serif">';
1526 $posthtml .= '<p>'.get_string('emailteachermailhtml', 'assignment', $info).'</p>';
1527 $posthtml .= '</font><hr />';
815b5ca6 1528 return $posthtml;
d8199f1d 1529 }
1530
7af1e882 1531 /**
1532 * Produces a list of links to the files uploaded by a user
1533 *
1534 * @param $userid int optional id of the user. If 0 then $USER->id is used.
1535 * @param $return boolean optional defaults to false. If true the list is returned rather than printed
1536 * @return string optional
1537 */
d8199f1d 1538 function print_user_files($userid=0, $return=false) {
d8199f1d 1539 global $CFG, $USER;
45fa3412 1540
d8199f1d 1541 if (!$userid) {
1542 if (!isloggedin()) {
1543 return '';
1544 }
1545 $userid = $USER->id;
1546 }
45fa3412 1547
70b2c772 1548 $filearea = $this->file_area_name($userid);
73097f07 1549
1550 $output = '';
45fa3412 1551
70b2c772 1552 if ($basedir = $this->file_area($userid)) {
73097f07 1553 if ($files = get_directory_list($basedir)) {
1ef048ae 1554 require_once($CFG->libdir.'/filelib.php');
73097f07 1555 foreach ($files as $key => $file) {
45fa3412 1556
73097f07 1557 $icon = mimeinfo('icon', $file);
45fa3412 1558
73097f07 1559 if ($CFG->slasharguments) {
d4156e80 1560 $ffurl = "$CFG->wwwroot/file.php/$filearea/$file";
73097f07 1561 } else {
d4156e80 1562 $ffurl = "$CFG->wwwroot/file.php?file=/$filearea/$file";
73097f07 1563 }
45fa3412 1564
0d905d9f 1565 $output .= '<img align="middle" src="'.$CFG->pixpath.'/f/'.$icon.'" class="icon" alt="'.$icon.'" />'.
9bf660b3 1566 '<a href="'.$ffurl.'" >'.$file.'</a><br />';
73097f07 1567 }
1568 }
1569 }
1570
1571 $output = '<div class="files">'.$output.'</div>';
1572
1573 if ($return) {
1574 return $output;
1575 }
1576 echo $output;
1577 }
1578
7af1e882 1579 /**
1580 * Count the files uploaded by a given user
1581 *
1582 * @param $userid int The user id
1583 * @return int
1584 */
70b2c772 1585 function count_user_files($userid) {
1586 global $CFG;
1587
1588 $filearea = $this->file_area_name($userid);
1589
c853b39f 1590 if ( is_dir($CFG->dataroot.'/'.$filearea) && $basedir = $this->file_area($userid)) {
70b2c772 1591 if ($files = get_directory_list($basedir)) {
1592 return count($files);
1593 }
1594 }
1595 return 0;
1596 }
73097f07 1597
7af1e882 1598 /**
1599 * Creates a directory file name, suitable for make_upload_directory()
1600 *
1601 * @param $userid int The user id
1602 * @return string path to file area
1603 */
70b2c772 1604 function file_area_name($userid) {
73097f07 1605 global $CFG;
45fa3412 1606
70b2c772 1607 return $this->course->id.'/'.$CFG->moddata.'/assignment/'.$this->assignment->id.'/'.$userid;
73097f07 1608 }
7af1e882 1609
1610 /**
1611 * Makes an upload directory
1612 *
1613 * @param $userid int The user id
1614 * @return string path to file area.
1615 */
70b2c772 1616 function file_area($userid) {
1617 return make_upload_directory( $this->file_area_name($userid) );
73097f07 1618 }
1619
7af1e882 1620 /**
1621 * Returns true if the student is allowed to submit
1622 *
1623 * Checks that the assignment has started and, if the option to prevent late
1624 * submissions is set, also checks that the assignment has not yet closed.
1625 * @return boolean
1626 */
f77cfb73 1627 function isopen() {
1628 $time = time();
1e4343a0 1629 if ($this->assignment->preventlate && $this->assignment->timedue) {
f77cfb73 1630 return ($this->assignment->timeavailable <= $time && $time <= $this->assignment->timedue);
1631 } else {
1632 return ($this->assignment->timeavailable <= $time);
1633 }
1634 }
1635
7af1e882 1636 /**
1637 * Return an outline of the user's interaction with the assignment
1638 *
1639 * The default method prints the grade and timemodified
1640 * @param $user object
1641 * @return object with properties ->info and ->time
1642 */
73097f07 1643 function user_outline($user) {
1644 if ($submission = $this->get_submission($user->id)) {
39e11905 1645
98be6ed8 1646 $result = new object();
39e11905 1647 $result->info = get_string('grade').': '.$this->display_grade($submission->grade);
73097f07 1648 $result->time = $submission->timemodified;
1649 return $result;
1650 }
1651 return NULL;
1652 }
7af1e882 1653
1654 /**
1655 * Print complete information about the user's interaction with the assignment
1656 *
1657 * @param $user object
1658 */
73097f07 1659 function user_complete($user) {
1660 if ($submission = $this->get_submission($user->id)) {
70b2c772 1661 if ($basedir = $this->file_area($user->id)) {
73097f07 1662 if ($files = get_directory_list($basedir)) {
1663 $countfiles = count($files)." ".get_string("uploadedfiles", "assignment");
1664 foreach ($files as $file) {
1665 $countfiles .= "; $file";
1666 }
1667 }
1668 }
45fa3412 1669
73097f07 1670 print_simple_box_start();
1671 echo get_string("lastmodified").": ";
9bf660b3 1672 echo userdate($submission->timemodified);
1673 echo $this->display_lateness($submission->timemodified);
45fa3412 1674
70b2c772 1675 $this->print_user_files($user->id);
45fa3412 1676
73097f07 1677 echo '<br />';
45fa3412 1678
73097f07 1679 if (empty($submission->timemarked)) {
1680 print_string("notgradedyet", "assignment");
1681 } else {
1682 $this->view_feedback($submission);
1683 }
45fa3412 1684
73097f07 1685 print_simple_box_end();
45fa3412 1686
73097f07 1687 } else {
1688 print_string("notsubmittedyet", "assignment");
1689 }
1690 }
1691
7af1e882 1692 /**
1693 * Return a string indicating how late a submission is
1694 *
45fa3412 1695 * @param $timesubmitted int
7af1e882 1696 * @return string
1697 */
70b2c772 1698 function display_lateness($timesubmitted) {
76a60031 1699 return assignment_display_lateness($timesubmitted, $this->assignment->timedue);
73097f07 1700 }
1701
55b4d096 1702 /**
1703 * Empty method stub for all delete actions.
1704 */
1705 function delete() {
1706 //nothing by default
1707 redirect('view.php?id='.$this->cm->id);
1708 }
1709
1710 /**
1711 * Empty custom feedback grading form.
1712 */
1713 function custom_feedbackform($submission, $return=false) {
1714 //nothing by default
1715 return '';
1716 }
73097f07 1717
09ba8e56 1718 /**
1719 * Add a get_coursemodule_info function in case any assignment type wants to add 'extra' information
1720 * for the course (see resource).
1721 *
1722 * Given a course_module object, this function returns any "extra" information that may be needed
1723 * when printing this activity in a course listing. See get_array_of_activities() in course/lib.php.
1724 *
1725 * @param $coursemodule object The coursemodule object (record).
1726 * @return object An object on information that the coures will know about (most noticeably, an icon).
1727 *
1728 */
1729 function get_coursemodule_info($coursemodule) {
1730 return false;
1731 }
1732
b0f2597e 1733} ////// End of the assignment_base class
d699cd1e 1734
18b8fbfa 1735
04eba58f 1736
b0f2597e 1737/// OTHER STANDARD FUNCTIONS ////////////////////////////////////////////////////////
1738
7af1e882 1739/**
1740 * Deletes an assignment instance
1741 *
1742 * This is done by calling the delete_instance() method of the assignment type class
1743 */
b0f2597e 1744function assignment_delete_instance($id){
26b90e70 1745 global $CFG;
1746
b0f2597e 1747 if (! $assignment = get_record('assignment', 'id', $id)) {
1748 return false;
26b90e70 1749 }
1750
b0f2597e 1751 require_once("$CFG->dirroot/mod/assignment/type/$assignment->assignmenttype/assignment.class.php");
1752 $assignmentclass = "assignment_$assignment->assignmenttype";
1753 $ass = new $assignmentclass();
1754 return $ass->delete_instance($assignment);
1755}
f466c9ed 1756
ac21ad39 1757
7af1e882 1758/**
1759 * Updates an assignment instance
1760 *
1761 * This is done by calling the update_instance() method of the assignment type class
1762 */
b0f2597e 1763function assignment_update_instance($assignment){
1764 global $CFG;
26b90e70 1765
200c19fb 1766 $assignment->assignmenttype = clean_param($assignment->assignmenttype, PARAM_SAFEDIR);
1767
b0f2597e 1768 require_once("$CFG->dirroot/mod/assignment/type/$assignment->assignmenttype/assignment.class.php");
1769 $assignmentclass = "assignment_$assignment->assignmenttype";
1770 $ass = new $assignmentclass();
1771 return $ass->update_instance($assignment);
45fa3412 1772}
26b90e70 1773
26b90e70 1774
7af1e882 1775/**
1776 * Adds an assignment instance
1777 *
1778 * This is done by calling the add_instance() method of the assignment type class
1779 */
b0f2597e 1780function assignment_add_instance($assignment) {
1781 global $CFG;
f466c9ed 1782
200c19fb 1783 $assignment->assignmenttype = clean_param($assignment->assignmenttype, PARAM_SAFEDIR);
1784
b0f2597e 1785 require_once("$CFG->dirroot/mod/assignment/type/$assignment->assignmenttype/assignment.class.php");
1786 $assignmentclass = "assignment_$assignment->assignmenttype";
1787 $ass = new $assignmentclass();
1788 return $ass->add_instance($assignment);
1789}
f466c9ed 1790
73097f07 1791
7af1e882 1792/**
1793 * Returns an outline of a user interaction with an assignment
1794 *
1795 * This is done by calling the user_outline() method of the assignment type class
1796 */
73097f07 1797function assignment_user_outline($course, $user, $mod, $assignment) {
1798 global $CFG;
1799
1800 require_once("$CFG->dirroot/mod/assignment/type/$assignment->assignmenttype/assignment.class.php");
1801 $assignmentclass = "assignment_$assignment->assignmenttype";
1802 $ass = new $assignmentclass($mod->id, $assignment, $mod, $course);
1803 return $ass->user_outline($user);
1804}
1805
7af1e882 1806/**
1807 * Prints the complete info about a user's interaction with an assignment
1808 *
1809 * This is done by calling the user_complete() method of the assignment type class
1810 */
73097f07 1811function assignment_user_complete($course, $user, $mod, $assignment) {
1812 global $CFG;
1813
1814 require_once("$CFG->dirroot/mod/assignment/type/$assignment->assignmenttype/assignment.class.php");
1815 $assignmentclass = "assignment_$assignment->assignmenttype";
1816 $ass = new $assignmentclass($mod->id, $assignment, $mod, $course);
1817 return $ass->user_complete($user);
1818}
1819
7af1e882 1820/**
1821 * Function to be run periodically according to the moodle cron
1822 *
1823 * Finds all assignment notifications that have yet to be mailed out, and mails them
1824 */
73097f07 1825function assignment_cron () {
73097f07 1826
1827 global $CFG, $USER;
1828
1829 /// Notices older than 1 day will not be mailed. This is to avoid the problem where
1830 /// cron has not been running for a long time, and then suddenly people are flooded
1831 /// with mail from the past few weeks or months
1832
1833 $timenow = time();
1834 $endtime = $timenow - $CFG->maxeditingtime;
1835 $starttime = $endtime - 24 * 3600; /// One day earlier
1836
1837 if ($submissions = assignment_get_unmailed_submissions($starttime, $endtime)) {
1838
98be6ed8 1839 $CFG->enablerecordcache = true; // We want all the caching we can get
1840
1841 $realuser = clone($USER);
1842
73097f07 1843 foreach ($submissions as $key => $submission) {
1844 if (! set_field("assignment_submissions", "mailed", "1", "id", "$submission->id")) {
1845 echo "Could not update the mailed field for id $submission->id. Not mailed.\n";
1846 unset($submissions[$key]);
1847 }
1848 }
1849
1850 $timenow = time();
1851
1852 foreach ($submissions as $submission) {
1853
1854 echo "Processing assignment submission $submission->id\n";
1855
1856 if (! $user = get_record("user", "id", "$submission->userid")) {
1857 echo "Could not find user $post->userid\n";
1858 continue;
1859 }
1860
73097f07 1861 if (! $course = get_record("course", "id", "$submission->course")) {
1862 echo "Could not find course $submission->course\n";
1863 continue;
1864 }
98be6ed8 1865
1866 /// Override the language and timezone of the "current" user, so that
1867 /// mail is customised for the receiver.
1868 $USER = $user;
1869 course_setup($course);
1870
dbbb712e 1871 if (!has_capability('moodle/course:view', get_context_instance(CONTEXT_COURSE, $submission->course), $user->id)) {
6ba65fa0 1872 echo fullname($user)." not an active participant in " . format_string($course->shortname) . "\n";
73097f07 1873 continue;
1874 }
1875
1876 if (! $teacher = get_record("user", "id", "$submission->teacher")) {
1877 echo "Could not find teacher $submission->teacher\n";
1878 continue;
1879 }
1880
1881 if (! $mod = get_coursemodule_from_instance("assignment", $submission->assignment, $course->id)) {
1882 echo "Could not find course module for assignment id $submission->assignment\n";
1883 continue;
1884 }
1885
1886 if (! $mod->visible) { /// Hold mail notification for hidden assignments until later
1887 continue;
1888 }
1889
1890 $strassignments = get_string("modulenameplural", "assignment");
1891 $strassignment = get_string("modulename", "assignment");
1892
98be6ed8 1893 $assignmentinfo = new object();
73097f07 1894 $assignmentinfo->teacher = fullname($teacher);
1895 $assignmentinfo->assignment = format_string($submission->name,true);
1896 $assignmentinfo->url = "$CFG->wwwroot/mod/assignment/view.php?id=$mod->id";
1897
1898 $postsubject = "$course->shortname: $strassignments: ".format_string($submission->name,true);
1899 $posttext = "$course->shortname -> $strassignments -> ".format_string($submission->name,true)."\n";
1900 $posttext .= "---------------------------------------------------------------------\n";
3f19bff3 1901 $posttext .= get_string("assignmentmail", "assignment", $assignmentinfo)."\n";
73097f07 1902 $posttext .= "---------------------------------------------------------------------\n";
1903
1904 if ($user->mailformat == 1) { // HTML
1905 $posthtml = "<p><font face=\"sans-serif\">".
1906 "<a href=\"$CFG->wwwroot/course/view.php?id=$course->id\">$course->shortname</a> ->".
1907 "<a href=\"$CFG->wwwroot/mod/assignment/index.php?id=$course->id\">$strassignments</a> ->".
1908 "<a href=\"$CFG->wwwroot/mod/assignment/view.php?id=$mod->id\">".format_string($submission->name,true)."</a></font></p>";
1909 $posthtml .= "<hr /><font face=\"sans-serif\">";
1910 $posthtml .= "<p>".get_string("assignmentmailhtml", "assignment", $assignmentinfo)."</p>";
1911 $posthtml .= "</font><hr />";
1912 } else {
1913 $posthtml = "";
1914 }
1915
1916 if (! email_to_user($user, $teacher, $postsubject, $posttext, $posthtml)) {
1917 echo "Error: assignment cron: Could not send out mail for id $submission->id to user $user->id ($user->email)\n";
1918 }
1919 }
98be6ed8 1920
1921 $USER = $realuser;
1922 course_setup(SITEID); // reset cron user language, theme and timezone settings
1923
73097f07 1924 }
1925
1926 return true;
1927}
1928
45fa3412 1929/**
1930 * Return grade for given user or all users.
1931 *
1932 * @param int $assignmentid id of assignment
1933 * @param int $userid optional user id, 0 means all users
1934 * @return array array of grades, false if none
1935 */
612607bd 1936function assignment_get_user_grades($assignment, $userid=0) {
45fa3412 1937 global $CFG;
1938
1939 $user = $userid ? "AND u.id = $userid" : "";
1940
ac9b0805 1941 $sql = "SELECT u.id, u.id AS userid, s.grade AS rawgrade, s.submissioncomment AS feedback, s.format AS feedbackformat
45fa3412 1942 FROM {$CFG->prefix}user u, {$CFG->prefix}assignment_submissions s
612607bd 1943 WHERE u.id = s.userid AND s.assignment = $assignment->id
4a1be95c 1944 $user";
45fa3412 1945
1946 return get_records_sql($sql);
1947}
1948
1949/**
1950 * Update grades by firing grade_updated event
1951 *
612607bd 1952 * @param object $assignment null means all assignments
45fa3412 1953 * @param int $userid specific user only, 0 mean all
1954 */
612607bd 1955function assignment_update_grades($assignment=null, $userid=0, $nullifnone=true) {
45fa3412 1956 global $CFG;
612607bd 1957 if (!function_exists('grade_update')) { //workaround for buggy PHP versions
1958 require_once($CFG->libdir.'/gradelib.php');
1959 }
45fa3412 1960
612607bd 1961 if ($assignment != null) {
1962 if ($grades = assignment_get_user_grades($assignment, $userid)) {
1963 foreach($grades as $k=>$v) {
ac9b0805 1964 if ($v->rawgrade == -1) {
1965 $grades[$k]->rawgrade = null;
45fa3412 1966 }
45fa3412 1967 }
b67ec72f 1968 grade_update('mod/assignment', $assignment->courseid, 'mod', 'assignment', $assignment->id, 0, $grades);
45fa3412 1969 }
1970
1971 } else {
4a1be95c 1972 $sql = "SELECT a.*, cm.idnumber as cmidnumber, a.course as courseid
1973 FROM {$CFG->prefix}assignment a, {$CFG->prefix}course_modules cm, {$CFG->prefix}modules m
1974 WHERE m.name='assignment' AND m.id=cm.module AND cm.instance=a.id";
45fa3412 1975 if ($rs = get_recordset_sql($sql)) {
1976 if ($rs->RecordCount() > 0) {
1977 while ($assignment = rs_fetch_next_record($rs)) {
612607bd 1978 assignment_grade_item_update($assignment);
1979 if ($assignment->grade != 0) {
1980 assignment_update_grades($assignment);
1981 }
45fa3412 1982 }
1983 }
1984 rs_close($rs);
1985 }
1986 }
1987}
1988
1989/**
612607bd 1990 * Create grade item for given assignment
45fa3412 1991 *
8b4fb44e 1992 * @param object $assignment object with extra cmidnumber
612607bd 1993 * @return int 0 if ok, error code otherwise
45fa3412 1994 */
1995function assignment_grade_item_update($assignment) {
612607bd 1996 global $CFG;
1997 if (!function_exists('grade_update')) { //workaround for buggy PHP versions
1998 require_once($CFG->libdir.'/gradelib.php');
45fa3412 1999 }
2000
8b4fb44e 2001 if (!isset($assignment->courseid)) {
2002 $assignment->courseid = $assignment->course;
2003 }
2004
612607bd 2005 $params = array('itemname'=>$assignment->name, 'idnumber'=>$assignment->cmidnumber);
45fa3412 2006
2007 if ($assignment->grade > 0) {
2008 $params['gradetype'] = GRADE_TYPE_VALUE;
2009 $params['grademax'] = $assignment->grade;
2010 $params['grademin'] = 0;
2011
2012 } else if ($assignment->grade < 0) {
2013 $params['gradetype'] = GRADE_TYPE_SCALE;
2014 $params['scaleid'] = -$assignment->grade;
2015
2016 } else {
612607bd 2017 $params['gradetype'] = GRADE_TYPE_NONE;
45fa3412 2018 }
2019
b67ec72f 2020 return grade_update('mod/assignment', $assignment->courseid, 'mod', 'assignment', $assignment->id, 0, NULL, $params);
45fa3412 2021}
2022
2023/**
2024 * Delete grade item for given assignment
2025 *
8b4fb44e 2026 * @param object $assignment object
612607bd 2027 * @return object assignment
45fa3412 2028 */
2029function assignment_grade_item_delete($assignment) {
612607bd 2030 global $CFG;
2031 require_once($CFG->libdir.'/gradelib.php');
2032
8b4fb44e 2033 if (!isset($assignment->courseid)) {
2034 $assignment->courseid = $assignment->course;
2035 }
2036
b67ec72f 2037 return grade_update('mod/assignment', $assignment->courseid, 'mod', 'assignment', $assignment->id, 0, NULL, array('deleted'=>1));
45fa3412 2038}
2039
2040/**
b67ec72f 2041 * Something wants to change the grade from outside using "grade_updated" event.
45fa3412 2042 *
45fa3412 2043 */
b67ec72f 2044function assignment_grade_handler($eventdata) {
45fa3412 2045 global $CFG, $USER;
2046
09c44262 2047 if ($eventdata->source == 'mod/assignment') {
2048 // event from assignment itself
2049 return true;
2050 }
2051
2052 if ($eventdata->itemtype != 'mod' or $eventdata->itemmodule != 'assignment') {
2053 //not for us - ignore it
2054 return true;
2055 }
2056
2057 if (!$assignment = get_record('assignment', 'id', $eventdata->iteminstance)) {
2058 return true;
2059 }
2060 if (! $course = get_record('course', 'id', $assignment->course)) {
2061 return true;
2062 }
2063 if (! $cm = get_coursemodule_from_instance('assignment', $assignment->id, $course->id)) {
2064 return true;
2065 }
2066
2067 // Load up the required assignment class
2068 require_once($CFG->dirroot.'/mod/assignment/type/'.$assignment->assignmenttype.'/assignment.class.php');
2069 $assignmentclass = 'assignment_'.$assignment->assignmenttype;
2070 $assignmentinstance = new $assignmentclass($cm->id, $assignment, $cm, $course);
2071
2072 $old = $assignmentinstance->get_submission($eventdata->userid, true); // Get or make one
2073 $submission = new object();
2074 $submission->id = $old->id;
2075 $submission->userid = $old->userid;
2076 $submission->teacher = $USER->id;
2077 $submission->timemarked = time();
2078
ac9b0805 2079 if (is_null($eventdata->rawgrade)) {
09c44262 2080 $submission->grade = -1;
2081 } else {
ac9b0805 2082 $submission->grade = (int)$eventdata->rawgrade; // round it for now
09c44262 2083 if ($old->grade != $submission->grade) {
2084 $submission->mailed = 0; // Make sure mail goes out (again, even)
2085 }
2086 }
2087
79944641 2088 if (isset($eventdata->feedback)) {
2089 $submission->submissioncomment = addslashes($eventdata->feedback);
2090 }
2091
2092 if (isset($eventdata->feedbackformat)) {
2093 $submission->format = (int)$eventdata->feedbackformat;
2094 }
09c44262 2095
79944641 2096 if (isset($eventdata->feedback) && ($old->submissioncomment != $eventdata->feedback or $old->format != $submission->format)) {
09c44262 2097 $submission->mailed = 0; // Make sure mail goes out (again, even)
2098 }
2099
2100 if (!update_record('assignment_submissions', $submission)) {
2101 //return false;
2102 }
2103
2104 // TODO: add proper logging
2105 add_to_log($course->id, 'assignment', 'update grades',
2106 'submissions.php?id='.$assignment->id.'&user='.$submission->userid, $submission->userid, $cm->id);
45fa3412 2107
2108 return true;
2109}
2110
7af1e882 2111/**
2112 * Returns the users with data in one assignment (students and teachers)
2113 *
2114 * @param $assignmentid int
2115 * @return array of user objects
2116 */
73097f07 2117function assignment_get_participants($assignmentid) {
73097f07 2118
2119 global $CFG;
2120
2121 //Get students
2122 $students = get_records_sql("SELECT DISTINCT u.id, u.id
2123 FROM {$CFG->prefix}user u,
2124 {$CFG->prefix}assignment_submissions a
2125 WHERE a.assignment = '$assignmentid' and
2126 u.id = a.userid");
2127 //Get teachers
2128 $teachers = get_records_sql("SELECT DISTINCT u.id, u.id
2129 FROM {$CFG->prefix}user u,
2130 {$CFG->prefix}assignment_submissions a
2131 WHERE a.assignment = '$assignmentid' and
2132 u.id = a.teacher");
2133
2134 //Add teachers to students
2135 if ($teachers) {
2136 foreach ($teachers as $teacher) {
2137 $students[$teacher->id] = $teacher;
2138 }
2139 }
2140 //Return students array (it contains an array of unique users)
2141 return ($students);
2142}
2143
7af1e882 2144/**
2145 * Checks if a scale is being used by an assignment
2146 *
2147 * This is used by the backup code to decide whether to back up a scale
2148 * @param $assignmentid int
2149 * @param $scaleid int
2150 * @return boolean True if the scale is used by the assignment
2151 */
2152function assignment_scale_used ($assignmentid, $scaleid) {
73097f07 2153
2154 $return = false;
2155
2156 $rec = get_record('assignment','id',$assignmentid,'grade',-$scaleid);
2157
2158 if (!empty($rec) && !empty($scaleid)) {
2159 $return = true;
2160 }
2161
2162 return $return;
2163}
2164
7af1e882 2165/**
2166 * Make sure up-to-date events are created for all assignment instances
2167 *
2168 * This standard function will check all instances of this module
2169 * and make sure there are up-to-date events created for each of them.
2170 * If courseid = 0, then every assignment event in the site is checked, else
2171 * only assignment events belonging to the course specified are checked.
2172 * This function is used, in its new format, by restore_refresh_events()
2173 *
2174 * @param $courseid int optional If zero then all assignments for all courses are covered
2175 * @return boolean Always returns true
2176 */
73097f07 2177function assignment_refresh_events($courseid = 0) {
73097f07 2178
2179 if ($courseid == 0) {
2180 if (! $assignments = get_records("assignment")) {
2181 return true;
2182 }
2183 } else {
2184 if (! $assignments = get_records("assignment", "course", $courseid)) {
2185 return true;
2186 }
2187 }
2188 $moduleid = get_field('modules', 'id', 'name', 'assignment');
2189
2190 foreach ($assignments as $assignment) {
2191 $event = NULL;
2192 $event->name = addslashes($assignment->name);
2193 $event->description = addslashes($assignment->description);
2194 $event->timestart = $assignment->timedue;
2195
2196 if ($event->id = get_field('event', 'id', 'modulename', 'assignment', 'instance', $assignment->id)) {
2197 update_event($event);
2198
2199 } else {
2200 $event->courseid = $assignment->course;
2201 $event->groupid = 0;
2202 $event->userid = 0;
2203 $event->modulename = 'assignment';
2204 $event->instance = $assignment->id;
2205 $event->eventtype = 'due';
2206 $event->timeduration = 0;
2207 $event->visible = get_field('course_modules', 'visible', 'module', $moduleid, 'instance', $assignment->id);
2208 add_event($event);
2209 }
2210
2211 }
2212 return true;
2213}
2214
7af1e882 2215/**
2216 * Print recent activity from all assignments in a given course
2217 *
2218 * This is used by the recent activity block
2219 */
73097f07 2220function assignment_print_recent_activity($course, $isteacher, $timestart) {
2221 global $CFG;
2222
2223 $content = false;
70b5660a 2224 $assignments = array();
73097f07 2225
2226 if (!$logs = get_records_select('log', 'time > \''.$timestart.'\' AND '.
2227 'course = \''.$course->id.'\' AND '.
2228 'module = \'assignment\' AND '.
2229 'action = \'upload\' ', 'time ASC')) {
2230 return false;
2231 }
2232
2233 foreach ($logs as $log) {
2234 //Create a temp valid module structure (course,id)
70b5660a 2235 $tempmod = new object();
73097f07 2236 $tempmod->course = $log->course;
2237 $tempmod->id = $log->info;
2238 //Obtain the visible property from the instance
2239 $modvisible = instance_is_visible($log->module,$tempmod);
2240
2241 //Only if the mod is visible
2242 if ($modvisible) {
70b5660a 2243 if ($info = assignment_log_info($log)) {
2244 $assignments[$log->info] = $info;
2245 $assignments[$log->info]->time = $log->time;
2246 $assignments[$log->info]->url = str_replace('&', '&amp;', $log->url);
2247 }
73097f07 2248 }
2249 }
2250
70b5660a 2251 if (!empty($assignments)) {
73097f07 2252 print_headline(get_string('newsubmissions', 'assignment').':');
2253 foreach ($assignments as $assignment) {
583b57b4 2254 print_recent_activity_note($assignment->time, $assignment, $assignment->name,
73097f07 2255 $CFG->wwwroot.'/mod/assignment/'.$assignment->url);
2256 }
2257 $content = true;
2258 }
2259
2260 return $content;
2261}
2262
2263
7af1e882 2264/**
2265 * Returns all assignments since a given time.
2266 *
2267 * If assignment is specified then this restricts the results
2268 */
73097f07 2269function assignment_get_recent_mod_activity(&$activities, &$index, $sincetime, $courseid, $assignment="0", $user="", $groupid="") {
73097f07 2270
2271 global $CFG;
2272
2273 if ($assignment) {
2274 $assignmentselect = " AND cm.id = '$assignment'";
2275 } else {
2276 $assignmentselect = "";
2277 }
2278 if ($user) {
2279 $userselect = " AND u.id = '$user'";
2280 } else {
2281 $userselect = "";
2282 }
2283
2284 $assignments = get_records_sql("SELECT asub.*, u.firstname, u.lastname, u.picture, u.id as userid,
2285 a.grade as maxgrade, name, cm.instance, cm.section, a.assignmenttype
2286 FROM {$CFG->prefix}assignment_submissions asub,
2287 {$CFG->prefix}user u,
2288 {$CFG->prefix}assignment a,
2289 {$CFG->prefix}course_modules cm
2290 WHERE asub.timemodified > '$sincetime'
2291 AND asub.userid = u.id $userselect
2292 AND a.id = asub.assignment $assignmentselect
2293 AND cm.course = '$courseid'
2294 AND cm.instance = a.id
2295 ORDER BY asub.timemodified ASC");
2296
2297 if (empty($assignments))
2298 return;
2299
2300 foreach ($assignments as $assignment) {
2301 if (empty($groupid) || ismember($groupid, $assignment->userid)) {
2302
2303 $tmpactivity = new Object;
2304
2305 $tmpactivity->type = "assignment";
2306 $tmpactivity->defaultindex = $index;
2307 $tmpactivity->instance = $assignment->instance;
2308 $tmpactivity->name = $assignment->name;
2309 $tmpactivity->section = $assignment->section;
2310
2311 $tmpactivity->content->grade = $assignment->grade;
2312 $tmpactivity->content->maxgrade = $assignment->maxgrade;
2313 $tmpactivity->content->type = $assignment->assignmenttype;
2314
2315 $tmpactivity->user->userid = $assignment->userid;
2316 $tmpactivity->user->fullname = fullname($assignment);
2317 $tmpactivity->user->picture = $assignment->picture;
2318
2319 $tmpactivity->timestamp = $assignment->timemodified;
2320
2321 $activities[] = $tmpactivity;
2322
2323 $index++;
2324 }
2325 }
2326
2327 return;
2328}
2329
7af1e882 2330/**
2331 * Print recent activity from all assignments in a given course
2332 *
2333 * This is used by course/recent.php
2334 */
73097f07 2335function assignment_print_recent_mod_activity($activity, $course, $detail=false) {
2336 global $CFG;
2337
2338 echo '<table border="0" cellpadding="3" cellspacing="0">';
2339
141a922c 2340 echo "<tr><td class=\"userpicture\" valign=\"top\">";
73097f07 2341 print_user_picture($activity->user->userid, $course, $activity->user->picture);
2342 echo "</td><td width=\"100%\"><font size=2>";
2343
2344 if ($detail) {
2345 echo "<img src=\"$CFG->modpixpath/$activity->type/icon.gif\" ".
0d905d9f 2346 "class=\"icon\" alt=\"$activity->type\"> ";
73097f07 2347 echo "<a href=\"$CFG->wwwroot/mod/assignment/view.php?id=" . $activity->instance . "\">"
2348 . format_string($activity->name,true) . "</a> - ";
2349
2350 }
2351
0bde6300 2352 if (has_capability('moodle/course:viewrecent', get_context_instance(CONTEXT_COURSE, $course))) {
73097f07 2353 $grades = "(" . $activity->content->grade . " / " . $activity->content->maxgrade . ") ";
2354
2355 $assignment->id = $activity->instance;
2356 $assignment->course = $course;
2357 $user->id = $activity->user->userid;
2358
2359 echo $grades;
2360 echo "<br />";
2361 }
2362 echo "<a href=\"$CFG->wwwroot/user/view.php?id="
2363 . $activity->user->userid . "&amp;course=$course\">"
2364 . $activity->user->fullname . "</a> ";
2365
2366 echo " - " . userdate($activity->timestamp);
2367
2368 echo "</font></td></tr>";
2369 echo "</table>";
73097f07 2370}
2371
2372/// GENERIC SQL FUNCTIONS
2373
7af1e882 2374/**
2375 * Fetch info from logs
2376 *
2377 * @param $log object with properties ->info (the assignment id) and ->userid
2378 * @return array with assignment name and user firstname and lastname
2379 */
73097f07 2380function assignment_log_info($log) {
2381 global $CFG;
2382 return get_record_sql("SELECT a.name, u.firstname, u.lastname
45fa3412 2383 FROM {$CFG->prefix}assignment a,
73097f07 2384 {$CFG->prefix}user u
45fa3412 2385 WHERE a.id = '$log->info'
73097f07 2386 AND u.id = '$log->userid'");
2387}
2388
7af1e882 2389/**
2390 * Return list of marked submissions that have not been mailed out for currently enrolled students
2391 *
2392 * @return array
2393 */
73097f07 2394function assignment_get_unmailed_submissions($starttime, $endtime) {
7af1e882 2395
73097f07 2396 global $CFG;
45fa3412 2397
73097f07 2398 return get_records_sql("SELECT s.*, a.course, a.name
45fa3412 2399 FROM {$CFG->prefix}assignment_submissions s,
4be6bced 2400 {$CFG->prefix}assignment a
45fa3412 2401 WHERE s.mailed = 0
2402 AND s.timemarked <= $endtime
ea8158c1 2403 AND s.timemarked >= $starttime
4be6bced 2404 AND s.assignment = a.id");
ea8158c1 2405
2406 /* return get_records_sql("SELECT s.*, a.course, a.name
45fa3412 2407 FROM {$CFG->prefix}assignment_submissions s,
73097f07 2408 {$CFG->prefix}assignment a,
2409 {$CFG->prefix}user_students us
45fa3412 2410 WHERE s.mailed = 0
2411 AND s.timemarked <= $endtime
73097f07 2412 AND s.timemarked >= $starttime
2413 AND s.assignment = a.id
2414 AND s.userid = us.userid
2415 AND a.course = us.course");
ea8158c1 2416 */
73097f07 2417}
2418
7af1e882 2419/**
2420 * Counts all real assignment submissions by ENROLLED students (not empty ones)
2421 *
2422 * There are also assignment type methods count_real_submissions() wich in the default
2423 * implementation simply call this function.
2424 * @param $groupid int optional If nonzero then count is restricted to this group
2425 * @return int The number of submissions
2426 */
73097f07 2427function assignment_count_real_submissions($assignment, $groupid=0) {
73097f07 2428 global $CFG;
2429
2430 if ($groupid) { /// How many in a particular group?
7bddd4b7 2431 return count_records_sql("SELECT COUNT(DISTINCT gm.userid, gm.groupid)
73097f07 2432 FROM {$CFG->prefix}assignment_submissions a,
e25cb710 2433 ".groups_members_from_sql()."
45fa3412 2434 WHERE a.assignment = $assignment->id
73097f07 2435 AND a.timemodified > 0
e25cb710 2436 AND ".groups_members_where_sql($groupid, 'a.userid'));
73097f07 2437 } else {
1648afb2 2438 $cm = get_coursemodule_from_instance('assignment', $assignment->id);
2439 $context = get_context_instance(CONTEXT_MODULE, $cm->id);
01194b77 2440
1648afb2 2441 // this is all the users with this capability set, in this context or higher
7bddd4b7 2442 if ($users = get_users_by_capability($context, 'mod/assignment:submit', '', '', '', '', 0, '', false)) {
01194b77 2443 foreach ($users as $user) {
2444 $array[] = $user->id;
2445 }
2446
2447 $userlists = '('.implode(',',$array).')';
2448
2449 return count_records_sql("SELECT COUNT(*)
2450 FROM {$CFG->prefix}assignment_submissions
45fa3412 2451 WHERE assignment = '$assignment->id'
01194b77 2452 AND timemodified > 0
2453 AND userid IN $userlists ");
2454 } else {
2455 return 0; // no users enroled in course
73097f07 2456 }
73097f07 2457 }
2458}
2459
7af1e882 2460
2461/**
2462 * Return all assignment submissions by ENROLLED students (even empty)
2463 *
2464 * There are also assignment type methods get_submissions() wich in the default
2465 * implementation simply call this function.
2466 * @param $sort string optional field names for the ORDER BY in the sql query
2467 * @param $dir string optional specifying the sort direction, defaults to DESC
2468 * @return array The submission objects indexed by id
2469 */
73097f07 2470function assignment_get_all_submissions($assignment, $sort="", $dir="DESC") {
2471/// Return all assignment submissions by ENROLLED students (even empty)
2472 global $CFG;
2473
2474 if ($sort == "lastname" or $sort == "firstname") {
2475 $sort = "u.$sort $dir";
2476 } else if (empty($sort)) {
2477 $sort = "a.timemodified DESC";
2478 } else {
2479 $sort = "a.$sort $dir";
2480 }
2481
ea8158c1 2482 /* not sure this is needed at all since assignmenet already has a course define, so this join?
73097f07 2483 $select = "s.course = '$assignment->course' AND";
2484 if ($assignment->course == SITEID) {
2485 $select = '';
ea8158c1 2486 }*/
45fa3412 2487
2488 return get_records_sql("SELECT a.*
2489 FROM {$CFG->prefix}assignment_submissions a,
ea8158c1 2490 {$CFG->prefix}user u
2491 WHERE u.id = a.userid
45fa3412 2492 AND a.assignment = '$assignment->id'
ea8158c1 2493 ORDER BY $sort");
45fa3412 2494
2495 /* return get_records_sql("SELECT a.*
2496 FROM {$CFG->prefix}assignment_submissions a,
73097f07 2497 {$CFG->prefix}user_students s,
2498 {$CFG->prefix}user u
2499 WHERE a.userid = s.userid
2500 AND u.id = a.userid
45fa3412 2501 AND $select a.assignment = '$assignment->id'
73097f07 2502 ORDER BY $sort");
ea8158c1 2503 */
73097f07 2504}
2505
09ba8e56 2506/**
2507 * Add a get_coursemodule_info function in case any assignment type wants to add 'extra' information
2508 * for the course (see resource).
2509 *
2510 * Given a course_module object, this function returns any "extra" information that may be needed
2511 * when printing this activity in a course listing. See get_array_of_activities() in course/lib.php.
2512 *
2513 * @param $coursemodule object The coursemodule object (record).
2514 * @return object An object on information that the coures will know about (most noticeably, an icon).
2515 *
2516 */
2517function assignment_get_coursemodule_info($coursemodule) {
2518 global $CFG;
2519
2520 if (! $assignment = get_record('assignment', 'id', $coursemodule->instance)) {
2521 return false;
2522 }
2523
2524 require_once("$CFG->dirroot/mod/assignment/type/$assignment->assignmenttype/assignment.class.php");
2525 $assignmentclass = "assignment_$assignment->assignmenttype";
2526 $ass = new $assignmentclass($coursemodule->id, $assignment);
2527
2528 return $ass->get_coursemodule_info($coursemodule);
2529}
73097f07 2530
2531
2532
2533/// OTHER GENERAL FUNCTIONS FOR ASSIGNMENTS ///////////////////////////////////////
2534
7af1e882 2535/**
2536 * Returns an array of installed assignment types indexed and sorted by name
2537 *
2538 * @return array The index is the name of the assignment type, the value its full name from the language strings
2539 */
b0f2597e 2540function assignment_types() {
2541 $types = array();
2542 $names = get_list_of_plugins('mod/assignment/type');
2543 foreach ($names as $name) {
2544 $types[$name] = get_string('type'.$name, 'assignment');
ffeca120 2545 }
b0f2597e 2546 asort($types);
2547 return $types;
f466c9ed 2548}
2549
7af1e882 2550/**
2551 * Executes upgrade scripts for assignment types when necessary
2552 */
b0f2597e 2553function assignment_upgrade_submodules() {
f1c1d2f1 2554 global $CFG;
26b90e70 2555
b0f2597e 2556 $types = assignment_types();
26b90e70 2557
d175966b 2558 include($CFG->dirroot.'/mod/assignment/version.php'); // defines $module with version etc
26b90e70 2559
d175966b 2560 foreach ($types as $type => $typename) {
26b90e70 2561
b0f2597e 2562 $fullpath = $CFG->dirroot.'/mod/assignment/type/'.$type;
26b90e70 2563
b0f2597e 2564 /// Check for an external version file (defines $submodule)
26b90e70 2565
b0f2597e 2566 if (!is_readable($fullpath .'/version.php')) {
2567 continue;
ffeca120 2568 }
b0f2597e 2569 include_once($fullpath .'/version.php');
26b90e70 2570
b0f2597e 2571 /// Check whether we need to upgrade
26b90e70 2572
b0f2597e 2573 if (!isset($submodule->version)) {
2574 continue;
2575 }
26b90e70 2576
b0f2597e 2577 /// Make sure this submodule will work with this assignment version
26b90e70 2578
d175966b 2579 if (isset($submodule->requires) and ($submodule->requires > $module->version)) {
b0f2597e 2580 notify("Assignment submodule '$type' is too new for your assignment");
2581 continue;
2582 }
f466c9ed 2583
a86a538f 2584 /// If the submodule is new, then let's install it!
f466c9ed 2585
b0f2597e 2586 $currentversion = 'assignment_'.$type.'_version';
f466c9ed 2587
a86a538f 2588 if (!isset($CFG->$currentversion)) { // First install!
2589 set_config($currentversion, $submodule->version); // Must keep track of version
2590
2591 if (!is_readable($fullpath .'/db/'.$CFG->dbtype.'.sql')) {
2592 continue;
2593 }
2594
583fad99 2595 upgrade_log_start();
a86a538f 2596 $db->debug=true;
2597 if (!modify_database($fullpath .'/db/'.$CFG->dbtype.'.sql')) {
2598 notify("Error installing tables for submodule '$type'!");
2599 }
2600 $db->debug=false;
2601 continue;
f466c9ed 2602 }
f466c9ed 2603
b0f2597e 2604 /// See if we need to upgrade
45fa3412 2605
b0f2597e 2606 if ($submodule->version <= $CFG->$currentversion) {
2607 continue;
59c005b7 2608 }
59c005b7 2609
b0f2597e 2610 /// Look for the upgrade file
59c005b7 2611
b0f2597e 2612 if (!is_readable($fullpath .'/db/'.$CFG->dbtype.'.php')) {
2613 continue;
2614 }
59c005b7 2615
b0f2597e 2616 include_once($fullpath .'/db/'. $CFG->dbtype .'.php'); // defines assignment_xxx_upgrade
59c005b7 2617
b0f2597e 2618 /// Perform the upgrade
59c005b7 2619
b0f2597e 2620 $upgrade_function = 'assignment_'.$type.'_upgrade';
2621 if (function_exists($upgrade_function)) {
583fad99 2622 upgrade_log_start();
b0f2597e 2623 $db->debug=true;
2624 if ($upgrade_function($CFG->$currentversion)) {
2625 $db->debug=false;
2626 set_config($currentversion, $submodule->version);
59c005b7 2627 }
b0f2597e 2628 $db->debug=false;
59c005b7 2629 }
2630 }
2631}
2632
84fa8f5f 2633function assignment_print_overview($courses, &$htmlarray) {
afe35ec4 2634
84fa8f5f 2635 global $USER, $CFG;
2636
2637 if (empty($courses) || !is_array($courses) || count($courses) == 0) {
2638 return array();
2639 }
2640
2641 if (!$assignments = get_all_instances_in_courses('assignment',$courses)) {
2642 return;
2643 }
2644
2645 // Do assignment_base::isopen() here without loading the whole thing for speed
2646 foreach ($assignments as $key => $assignment) {
2647 $time = time();
d6da4a1a 2648 if ($assignment->timedue) {
2649 if ($assignment->preventlate) {
2650 $isopen = ($assignment->timeavailable <= $time && $time <= $assignment->timedue);
2651 } else {
2652 $isopen = ($assignment->timeavailable <= $time);
2653 }
84fa8f5f 2654 }
d6da4a1a 2655 if (empty($isopen) || empty($assignment->timedue)) {
84fa8f5f 2656 unset($assignments[$key]);
2657 }
2658 }
2659
2660 $strduedate = get_string('duedate', 'assignment');
8f643c81 2661 $strduedateno = get_string('duedateno', 'assignment');
84fa8f5f 2662 $strgraded = get_string('graded', 'assignment');
2663 $strnotgradedyet = get_string('notgradedyet', 'assignment');
2664 $strnotsubmittedyet = get_string('notsubmittedyet', 'assignment');
2665 $strsubmitted = get_string('submitted', 'assignment');
76a60031 2666 $strassignment = get_string('modulename', 'assignment');
c664a036 2667 $strreviewed = get_string('reviewed','assignment');
84fa8f5f 2668
2669 foreach ($assignments as $assignment) {
a2a37336 2670 $str = '<div class="assignment overview"><div class="name">'.$strassignment. ': '.
a7a74d77 2671 '<a '.($assignment->visible ? '':' class="dimmed"').
76a60031 2672 'title="'.$strassignment.'" href="'.$CFG->wwwroot.
a7a74d77 2673 '/mod/assignment/view.php?id='.$assignment->coursemodule.'">'.
5d45c04f 2674 $assignment->name.'</a></div>';
8f643c81 2675 if ($assignment->timedue) {
2676 $str .= '<div class="info">'.$strduedate.': '.userdate($assignment->timedue).'</div>';
2677 } else {
2678 $str .= '<div class="info">'.$strduedateno.'</div>';
2679 }
793a8c3a 2680 $context = get_context_instance(CONTEXT_MODULE, $assignment->coursemodule);
0468976c 2681 if (has_capability('mod/assignment:grade', $context)) {
45fa3412 2682
ea8158c1 2683 // count how many people can submit
2684 $submissions = 0; // init
7bddd4b7 2685 if ($students = get_users_by_capability($context, 'mod/assignment:submit', '', '', '', '', 0, '', false)) {
2686 foreach ($students as $student) {
afe35ec4 2687 if (get_records_sql("SELECT id,id FROM {$CFG->prefix}assignment_submissions
2688 WHERE assignment = $assignment->id AND
2689 userid = $student->id AND
2690 teacher = 0 AND
2691 timemarked = 0")) {
45fa3412 2692 $submissions++;
c2adcc90 2693 }
ea8158c1 2694 }
2695 }
45fa3412 2696
84fa8f5f 2697 if ($submissions) {
2698 $str .= get_string('submissionsnotgraded', 'assignment', $submissions);
2699 }
2700 } else {
2701 $sql = "SELECT *
2702 FROM {$CFG->prefix}assignment_submissions
b3d4840d 2703 WHERE userid = '$USER->id'
2704 AND assignment = '{$assignment->id}'";
84fa8f5f 2705 if ($submission = get_record_sql($sql)) {
2706 if ($submission->teacher == 0 && $submission->timemarked == 0) {
2707 $str .= $strsubmitted . ', ' . $strnotgradedyet;
c664a036 2708 } else if ($submission->grade <= 0) {
2709 $str .= $strsubmitted . ', ' . $strreviewed;
84fa8f5f 2710 } else {
2711 $str .= $strsubmitted . ', ' . $strgraded;
2712 }
2713 } else {
76a60031 2714 $str .= $strnotsubmittedyet . ' ' . assignment_display_lateness(time(), $assignment->timedue);
84fa8f5f 2715 }
2716 }
a7a74d77 2717 $str .= '</div>';
76a60031 2718 if (empty($htmlarray[$assignment->course]['assignment'])) {
2719 $htmlarray[$assignment->course]['assignment'] = $str;
2720 } else {
2721 $htmlarray[$assignment->course]['assignment'] .= $str;
2722 }
2723 }
2724}
2725
2726function assignment_display_lateness($timesubmitted, $timedue) {
2727 if (!$timedue) {
2728 return '';
2729 }
2730 $time = $timedue - $timesubmitted;
2731 if ($time < 0) {
2732 $timetext = get_string('late', 'assignment', format_time($time));
2733 return ' (<span class="late">'.$timetext.'</span>)';
2734 } else {
2735 $timetext = get_string('early', 'assignment', format_time($time));
2736 return ' (<span class="early">'.$timetext.'</span>)';
84fa8f5f 2737 }
2738}
2739
ac15a2d5 2740function assignment_get_view_actions() {
2741 return array('view');
2742}
2743
2744function assignment_get_post_actions() {
2745 return array('upload');
2746}
2747
89bfeee0 2748function assignment_get_types() {
0ac1cfc3 2749 global $CFG;
89bfeee0 2750 $types = array();
2751
2752 $type = new object();
2753 $type->modclass = MOD_CLASS_ACTIVITY;
2754 $type->type = "assignment_group_start";
2755 $type->typestr = '--'.get_string('modulenameplural', 'assignment');
2756 $types[] = $type;
2757
2758 $standardassignments = array('upload','online','uploadsingle','offline');
2759 foreach ($standardassignments as $assignmenttype) {
2760 $type = new object();
2761 $type->modclass = MOD_CLASS_ACTIVITY;
2762 $type->type = "assignment&amp;type=$assignmenttype";
2763 $type->typestr = get_string("type$assignmenttype", 'assignment');
2764 $types[] = $type;
2765 }
2766
2767 /// Drop-in extra assignment types
2768 $assignmenttypes = get_list_of_plugins('mod/assignment/type');
2769 foreach ($assignmenttypes as $assignmenttype) {
2770 if (!empty($CFG->{'assignment_hide_'.$assignmenttype})) { // Not wanted
2771 continue;
2772 }
2773 if (!in_array($assignmenttype, $standardassignments)) {
2774 $type = new object();
2775 $type->modclass = MOD_CLASS_ACTIVITY;
2776 $type->type = "assignment&amp;type=$assignmenttype";
2777 $type->typestr = get_string("type$assignmenttype", 'assignment');
2778 $types[] = $type;
2779 }
2780 }
2781
2782 $type = new object();
2783 $type->modclass = MOD_CLASS_ACTIVITY;
2784 $type->type = "assignment_group_end";
2785 $type->typestr = '--';
2786 $types[] = $type;
2787
2788 return $types;
2789}
2790
76a60031 2791?>