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