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