MDL-9657 assignment submission finalisation now independent from grade
[moodle-linuxchix.git] / mod / assignment / lib.php
blob70d58f1207e49aa95406ae0cc944cc6e501b764b
1 <?PHP // $Id$
2 /**
3 * assignment_base is the base class for assignment types
5 * This class provides all the functionality for an assignment
6 */
8 DEFINE ('ASSIGNMENT_COUNT_WORDS', 1);
9 DEFINE ('ASSIGNMENT_COUNT_LETTERS', 2);
11 /**
12 * Standard base class for all assignment submodules (assignment types).
14 class assignment_base {
16 var $cm;
17 var $course;
18 var $assignment;
19 var $strassignment;
20 var $strassignments;
21 var $strsubmissions;
22 var $strlastmodified;
23 var $pagetitle;
24 var $usehtmleditor;
25 var $defaultformat;
26 var $context;
27 var $type;
29 /**
30 * Constructor for the base assignment class
32 * Constructor for the base assignment class.
33 * If cmid is set create the cm, course, assignment objects.
34 * If the assignment is hidden and the user is not a teacher then
35 * this prints a page header and notice.
37 * @param cmid integer, the current course module id - not set for new assignments
38 * @param assignment object, usually null, but if we have it we pass it to save db access
39 * @param cm object, usually null, but if we have it we pass it to save db access
40 * @param course object, usually null, but if we have it we pass it to save db access
42 function assignment_base($cmid='staticonly', $assignment=NULL, $cm=NULL, $course=NULL) {
43 global $COURSE;
45 if ($cmid == 'staticonly') {
46 //use static functions only!
47 return;
50 global $CFG;
52 if ($cm) {
53 $this->cm = $cm;
54 } else if (! $this->cm = get_coursemodule_from_id('assignment', $cmid)) {
55 error('Course Module ID was incorrect');
58 $this->context = get_context_instance(CONTEXT_MODULE, $this->cm->id);
60 if ($course) {
61 $this->course = $course;
62 } else if ($this->cm->course == $COURSE->id) {
63 $this->course = $COURSE;
64 } else if (! $this->course = get_record('course', 'id', $this->cm->course)) {
65 error('Course is misconfigured');
68 if ($assignment) {
69 $this->assignment = $assignment;
70 } else if (! $this->assignment = get_record('assignment', 'id', $this->cm->instance)) {
71 error('assignment ID was incorrect');
74 $this->assignment->cmidnumber = $this->cm->id; // compatibility with modedit assignment obj
75 $this->assignment->courseid = $this->course->id; // compatibility with modedit assignment obj
77 $this->strassignment = get_string('modulename', 'assignment');
78 $this->strassignments = get_string('modulenameplural', 'assignment');
79 $this->strsubmissions = get_string('submissions', 'assignment');
80 $this->strlastmodified = get_string('lastmodified');
81 $this->pagetitle = strip_tags($this->course->shortname.': '.$this->strassignment.': '.format_string($this->assignment->name,true));
83 // visibility handled by require_login() with $cm parameter
84 // get current group only when really needed
86 /// Set up things for a HTML editor if it's needed
87 if ($this->usehtmleditor = can_use_html_editor()) {
88 $this->defaultformat = FORMAT_HTML;
89 } else {
90 $this->defaultformat = FORMAT_MOODLE;
94 /**
95 * Display the assignment, used by view.php
97 * This in turn calls the methods producing individual parts of the page
99 function view() {
101 $context = get_context_instance(CONTEXT_MODULE,$this->cm->id);
102 require_capability('mod/assignment:view', $context);
104 add_to_log($this->course->id, "assignment", "view", "view.php?id={$this->cm->id}",
105 $this->assignment->id, $this->cm->id);
107 $this->view_header();
109 $this->view_intro();
111 $this->view_dates();
113 $this->view_feedback();
115 $this->view_footer();
119 * Display the header and top of a page
121 * (this doesn't change much for assignment types)
122 * This is used by the view() method to print the header of view.php but
123 * it can be used on other pages in which case the string to denote the
124 * page in the navigation trail should be passed as an argument
126 * @param $subpage string Description of subpage to be used in navigation trail
128 function view_header($subpage='') {
130 global $CFG;
133 if ($subpage) {
134 $navigation = build_navigation($subpage, $this->cm);
135 } else {
136 $navigation = build_navigation('', $this->cm);
139 print_header($this->pagetitle, $this->course->fullname, $navigation, '', '',
140 true, update_module_button($this->cm->id, $this->course->id, $this->strassignment),
141 navmenu($this->course, $this->cm));
143 groups_print_activity_menu($this->cm, 'view.php?id=' . $this->cm->id);
145 echo '<div class="reportlink">'.$this->submittedlink().'</div>';
146 echo '<div class="clearer"></div>';
151 * Display the assignment intro
153 * This will most likely be extended by assignment type plug-ins
154 * The default implementation prints the assignment description in a box
156 function view_intro() {
157 print_simple_box_start('center', '', '', 0, 'generalbox', 'intro');
158 $formatoptions = new stdClass;
159 $formatoptions->noclean = true;
160 echo format_text($this->assignment->description, $this->assignment->format, $formatoptions);
161 print_simple_box_end();
165 * Display the assignment dates
167 * Prints the assignment start and end dates in a box.
168 * This will be suitable for most assignment types
170 function view_dates() {
171 if (!$this->assignment->timeavailable && !$this->assignment->timedue) {
172 return;
175 print_simple_box_start('center', '', '', 0, 'generalbox', 'dates');
176 echo '<table>';
177 if ($this->assignment->timeavailable) {
178 echo '<tr><td class="c0">'.get_string('availabledate','assignment').':</td>';
179 echo ' <td class="c1">'.userdate($this->assignment->timeavailable).'</td></tr>';
181 if ($this->assignment->timedue) {
182 echo '<tr><td class="c0">'.get_string('duedate','assignment').':</td>';
183 echo ' <td class="c1">'.userdate($this->assignment->timedue).'</td></tr>';
185 echo '</table>';
186 print_simple_box_end();
191 * Display the bottom and footer of a page
193 * This default method just prints the footer.
194 * This will be suitable for most assignment types
196 function view_footer() {
197 print_footer($this->course);
201 * Display the feedback to the student
203 * This default method prints the teacher picture and name, date when marked,
204 * grade and teacher submissioncomment.
206 * @param $submission object The submission object or NULL in which case it will be loaded
208 function view_feedback($submission=NULL) {
209 global $USER, $CFG;
210 require_once($CFG->libdir.'/gradelib.php');
212 if (!has_capability('mod/assignment:submit', $this->context, $USER->id, false)) {
213 // can not submit assignments -> no feedback
214 return;
217 if (!$submission) { /// Get submission for this assignment
218 $submission = $this->get_submission($USER->id);
221 $grading_info = grade_get_grades($this->course->id, 'mod', 'assignment', $this->assignment->id, $USER->id);
222 $item = $grading_info->items[0];
223 $grade = $item->grades[$USER->id];
225 if ($grade->hidden or $grade->grade === false) { // hidden or error
226 return;
229 if ($grade->grade === null and empty($grade->str_feedback)) { /// Nothing to show yet
230 return;
233 $graded_date = $grade->dategraded;
234 $graded_by = $grade->usermodified;
236 /// We need the teacher info
237 $teacher = get_record('user', 'id', $graded_by);
239 /// Print the feedback
240 print_heading(get_string('feedbackfromteacher', 'assignment', $this->course->teacher)); // TODO: fix teacher string
242 echo '<table cellspacing="0" class="feedback">';
244 echo '<tr>';
245 echo '<td class="left picture">';
246 if ($teacher) {
247 print_user_picture($teacher, $this->course->id, $teacher->picture);
249 echo '</td>';
250 echo '<td class="topic">';
251 echo '<div class="from">';
252 if ($teacher) {
253 echo '<div class="fullname">'.fullname($teacher).'</div>';
255 echo '<div class="time">'.userdate($graded_date).'</div>';
256 echo '</div>';
257 echo '</td>';
258 echo '</tr>';
260 echo '<tr>';
261 echo '<td class="left side">&nbsp;</td>';
262 echo '<td class="content">';
263 echo '<div class="grade">';
264 echo get_string("grade").': '.$grade->str_long_grade;
265 echo '</div>';
266 echo '<div class="clearer"></div>';
268 echo '<div class="comment">';
269 echo $grade->str_feedback;
270 echo '</div>';
271 echo '</tr>';
273 echo '</table>';
277 * Returns a link with info about the state of the assignment submissions
279 * This is used by view_header to put this link at the top right of the page.
280 * For teachers it gives the number of submitted assignments with a link
281 * For students it gives the time of their submission.
282 * This will be suitable for most assignment types.
283 * @param bool $allgroup print all groups info if user can access all groups, suitable for index.php
284 * @return string
286 function submittedlink($allgroups=false) {
287 global $USER;
289 $submitted = '';
291 $context = get_context_instance(CONTEXT_MODULE,$this->cm->id);
292 if (has_capability('mod/assignment:grade', $context)) {
293 if ($allgroups and has_capability('moodle/site:accessallgroups', $context)) {
294 $group = 0;
295 } else {
296 $group = groups_get_activity_group($this->cm);
298 if ($count = $this->count_real_submissions($group)) {
299 $submitted = '<a href="submissions.php?id='.$this->cm->id.'">'.
300 get_string('viewsubmissions', 'assignment', $count).'</a>';
301 } else {
302 $submitted = '<a href="submissions.php?id='.$this->cm->id.'">'.
303 get_string('noattempts', 'assignment').'</a>';
305 } else {
306 if (!empty($USER->id)) {
307 if ($submission = $this->get_submission($USER->id)) {
308 if ($submission->timemodified) {
309 if ($submission->timemodified <= $this->assignment->timedue || empty($this->assignment->timedue)) {
310 $submitted = '<span class="early">'.userdate($submission->timemodified).'</span>';
311 } else {
312 $submitted = '<span class="late">'.userdate($submission->timemodified).'</span>';
319 return $submitted;
323 function setup_elements(&$mform) {
328 * Create a new assignment activity
330 * Given an object containing all the necessary data,
331 * (defined by the form in mod.html) this function
332 * will create a new instance and return the id number
333 * of the new instance.
334 * The due data is added to the calendar
335 * This is common to all assignment types.
337 * @param $assignment object The data from the form on mod.html
338 * @return int The id of the assignment
340 function add_instance($assignment) {
341 global $COURSE;
343 $assignment->timemodified = time();
344 $assignment->courseid = $assignment->course;
346 if ($returnid = insert_record("assignment", $assignment)) {
347 $assignment->id = $returnid;
349 if ($assignment->timedue) {
350 $event = new object();
351 $event->name = $assignment->name;
352 $event->description = $assignment->description;
353 $event->courseid = $assignment->course;
354 $event->groupid = 0;
355 $event->userid = 0;
356 $event->modulename = 'assignment';
357 $event->instance = $returnid;
358 $event->eventtype = 'due';
359 $event->timestart = $assignment->timedue;
360 $event->timeduration = 0;
362 add_event($event);
365 $assignment = stripslashes_recursive($assignment);
366 assignment_grade_item_update($assignment);
371 return $returnid;
375 * Deletes an assignment activity
377 * Deletes all database records, files and calendar events for this assignment.
378 * @param $assignment object The assignment to be deleted
379 * @return boolean False indicates error
381 function delete_instance($assignment) {
382 global $CFG;
384 $assignment->courseid = $assignment->course;
386 $result = true;
388 if (! delete_records('assignment_submissions', 'assignment', $assignment->id)) {
389 $result = false;
392 if (! delete_records('assignment', 'id', $assignment->id)) {
393 $result = false;
396 if (! delete_records('event', 'modulename', 'assignment', 'instance', $assignment->id)) {
397 $result = false;
400 // delete file area with all attachments - ignore errors
401 require_once($CFG->libdir.'/filelib.php');
402 fulldelete($CFG->dataroot.'/'.$assignment->course.'/'.$CFG->moddata.'/assignment/'.$assignment->id);
404 assignment_grade_item_delete($assignment);
406 return $result;
410 * Updates a new assignment activity
412 * Given an object containing all the necessary data,
413 * (defined by the form in mod.html) this function
414 * will update the assignment instance and return the id number
415 * The due date is updated in the calendar
416 * This is common to all assignment types.
418 * @param $assignment object The data from the form on mod.html
419 * @return int The assignment id
421 function update_instance($assignment) {
422 global $COURSE;
424 $assignment->timemodified = time();
426 $assignment->id = $assignment->instance;
427 $assignment->courseid = $assignment->course;
429 if (!update_record('assignment', $assignment)) {
430 return false;
433 if ($assignment->timedue) {
434 $event = new object();
436 if ($event->id = get_field('event', 'id', 'modulename', 'assignment', 'instance', $assignment->id)) {
438 $event->name = $assignment->name;
439 $event->description = $assignment->description;
440 $event->timestart = $assignment->timedue;
442 update_event($event);
443 } else {
444 $event = new object();
445 $event->name = $assignment->name;
446 $event->description = $assignment->description;
447 $event->courseid = $assignment->course;
448 $event->groupid = 0;
449 $event->userid = 0;
450 $event->modulename = 'assignment';
451 $event->instance = $assignment->id;
452 $event->eventtype = 'due';
453 $event->timestart = $assignment->timedue;
454 $event->timeduration = 0;
456 add_event($event);
458 } else {
459 delete_records('event', 'modulename', 'assignment', 'instance', $assignment->id);
462 // get existing grade item
463 $assignment = stripslashes_recursive($assignment);
465 assignment_grade_item_update($assignment);
467 return true;
471 * Update grade item for this submission.
473 function update_grade($submission) {
474 assignment_update_grades($this->assignment, $submission->userid);
478 * Top-level function for handling of submissions called by submissions.php
480 * This is for handling the teacher interaction with the grading interface
481 * This should be suitable for most assignment types.
483 * @param $mode string Specifies the kind of teacher interaction taking place
485 function submissions($mode) {
486 ///The main switch is changed to facilitate
487 ///1) Batch fast grading
488 ///2) Skip to the next one on the popup
489 ///3) Save and Skip to the next one on the popup
491 //make user global so we can use the id
492 global $USER;
494 switch ($mode) {
495 case 'grade': // We are in a popup window grading
496 if ($submission = $this->process_feedback()) {
497 //IE needs proper header with encoding
498 print_header(get_string('feedback', 'assignment').':'.format_string($this->assignment->name));
499 print_heading(get_string('changessaved'));
500 print $this->update_main_listing($submission);
502 close_window();
503 break;
505 case 'single': // We are in a popup window displaying submission
506 $this->display_submission();
507 break;
509 case 'all': // Main window, display everything
510 $this->display_submissions();
511 break;
513 case 'fastgrade':
514 ///do the fast grading stuff - this process should work for all 3 subclasses
515 $grading = false;
516 $commenting = false;
517 $col = false;
518 if (isset($_POST['submissioncomment'])) {
519 $col = 'submissioncomment';
520 $commenting = true;
522 if (isset($_POST['menu'])) {
523 $col = 'menu';
524 $grading = true;
526 if (!$col) {
527 //both submissioncomment and grade columns collapsed..
528 $this->display_submissions();
529 break;
531 foreach ($_POST[$col] as $id => $unusedvalue){
533 $id = (int)$id; //clean parameter name
535 $this->process_outcomes($id);
537 if (!$submission = $this->get_submission($id)) {
538 $submission = $this->prepare_new_submission($id);
539 $newsubmission = true;
540 } else {
541 $newsubmission = false;
543 unset($submission->data1); // Don't need to update this.
544 unset($submission->data2); // Don't need to update this.
546 //for fast grade, we need to check if any changes take place
547 $updatedb = false;
549 if ($grading) {
550 $grade = $_POST['menu'][$id];
551 $updatedb = $updatedb || ($submission->grade != $grade);
552 $submission->grade = $grade;
553 } else {
554 if (!$newsubmission) {
555 unset($submission->grade); // Don't need to update this.
558 if ($commenting) {
559 $commentvalue = trim($_POST['submissioncomment'][$id]);
560 $updatedb = $updatedb || ($submission->submissioncomment != stripslashes($commentvalue));
561 $submission->submissioncomment = $commentvalue;
562 } else {
563 unset($submission->submissioncomment); // Don't need to update this.
566 $submission->teacher = $USER->id;
567 $submission->mailed = $updatedb?0:$submission->mailed;//only change if it's an update
568 $submission->timemarked = time();
570 //if it is not an update, we don't change the last modified time etc.
571 //this will also not write into database if no submissioncomment and grade is entered.
573 if ($updatedb){
574 if ($newsubmission) {
575 if (!$sid = insert_record('assignment_submissions', $submission)) {
576 return false;
578 $submission->id = $sid;
579 } else {
580 if (!update_record('assignment_submissions', $submission)) {
581 return false;
585 // triger grade event
586 $this->update_grade($submission);
588 //add to log only if updating
589 add_to_log($this->course->id, 'assignment', 'update grades',
590 'submissions.php?id='.$this->assignment->id.'&user='.$submission->userid,
591 $submission->userid, $this->cm->id);
596 $message = notify(get_string('changessaved'), 'notifysuccess', 'center', true);
598 $this->display_submissions($message);
599 break;
602 case 'next':
603 /// We are currently in pop up, but we want to skip to next one without saving.
604 /// This turns out to be similar to a single case
605 /// The URL used is for the next submission.
607 $this->display_submission();
608 break;
610 case 'saveandnext':
611 ///We are in pop up. save the current one and go to the next one.
612 //first we save the current changes
613 if ($submission = $this->process_feedback()) {
614 //print_heading(get_string('changessaved'));
615 $extra_javascript = $this->update_main_listing($submission);
618 //then we display the next submission
619 $this->display_submission($extra_javascript);
620 break;
622 default:
623 echo "something seriously is wrong!!";
624 break;
629 * Helper method updating the listing on the main script from popup using javascript
631 * @param $submission object The submission whose data is to be updated on the main page
633 function update_main_listing($submission) {
634 global $SESSION, $CFG;
636 $output = '';
638 $perpage = get_user_preferences('assignment_perpage', 10);
640 $quickgrade = get_user_preferences('assignment_quickgrade', 0);
642 /// Run some Javascript to try and update the parent page
643 $output .= '<script type="text/javascript">'."\n<!--\n";
644 if (empty($SESSION->flextable['mod-assignment-submissions']->collapse['submissioncomment'])) {
645 if ($quickgrade){
646 $output.= 'opener.document.getElementById("submissioncomment'.$submission->userid.'").value="'
647 .trim($submission->submissioncomment).'";'."\n";
648 } else {
649 $output.= 'opener.document.getElementById("com'.$submission->userid.
650 '").innerHTML="'.shorten_text(trim(strip_tags($submission->submissioncomment)), 15)."\";\n";
654 if (empty($SESSION->flextable['mod-assignment-submissions']->collapse['grade'])) {
655 //echo optional_param('menuindex');
656 if ($quickgrade){
657 $output.= 'opener.document.getElementById("menumenu'.$submission->userid.
658 '").selectedIndex="'.optional_param('menuindex', 0, PARAM_INT).'";'."\n";
659 } else {
660 $output.= 'opener.document.getElementById("g'.$submission->userid.'").innerHTML="'.
661 $this->display_grade($submission->grade)."\";\n";
664 //need to add student's assignments in there too.
665 if (empty($SESSION->flextable['mod-assignment-submissions']->collapse['timemodified']) &&
666 $submission->timemodified) {
667 $output.= 'opener.document.getElementById("ts'.$submission->userid.
668 '").innerHTML="'.addslashes_js($this->print_student_answer($submission->userid)).userdate($submission->timemodified)."\";\n";
671 if (empty($SESSION->flextable['mod-assignment-submissions']->collapse['timemarked']) &&
672 $submission->timemarked) {
673 $output.= 'opener.document.getElementById("tt'.$submission->userid.
674 '").innerHTML="'.userdate($submission->timemarked)."\";\n";
677 if (empty($SESSION->flextable['mod-assignment-submissions']->collapse['status'])) {
678 $output.= 'opener.document.getElementById("up'.$submission->userid.'").className="s1";';
679 $buttontext = get_string('update');
680 $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),
681 'grade'.$submission->userid, $buttontext, 450, 700, $buttontext, 'none', true, 'button'.$submission->userid);
682 $output.= 'opener.document.getElementById("up'.$submission->userid.'").innerHTML="'.addslashes_js($button).'";';
685 $grading_info = grade_get_grades($this->course->id, 'mod', 'assignment', $this->assignment->id, $submission->userid);
687 if (empty($SESSION->flextable['mod-assignment-submissions']->collapse['finalgrade'])) {
688 $output.= 'opener.document.getElementById("finalgrade_'.$submission->userid.
689 '").innerHTML="'.$grading_info->items[0]->grades[$submission->userid]->str_grade.'";'."\n";
692 if (!empty($CFG->enableoutcomes) and empty($SESSION->flextable['mod-assignment-submissions']->collapse['outcome'])) {
694 if (!empty($grading_info->outcomes)) {
695 foreach($grading_info->outcomes as $n=>$outcome) {
696 if ($outcome->grades[$submission->userid]->locked) {
697 continue;
700 if ($quickgrade){
701 $output.= 'opener.document.getElementById("outcome_'.$n.'_'.$submission->userid.
702 '").selectedIndex="'.$outcome->grades[$submission->userid]->grade.'";'."\n";
704 } else {
705 $options = make_grades_menu(-$outcome->scaleid);
706 $options[0] = get_string('nooutcome', 'grades');
707 $output.= 'opener.document.getElementById("outcome_'.$n.'_'.$submission->userid.'").innerHTML="'.$options[$outcome->grades[$submission->userid]->grade]."\";\n";
714 $output .= "\n-->\n</script>";
715 return $output;
719 * Return a grade in user-friendly form, whether it's a scale or not
721 * @param $grade
722 * @return string User-friendly representation of grade
724 function display_grade($grade) {
726 static $scalegrades = array(); // Cache scales for each assignment - they might have different scales!!
728 if ($this->assignment->grade >= 0) { // Normal number
729 if ($grade == -1) {
730 return '-';
731 } else {
732 return $grade.' / '.$this->assignment->grade;
735 } else { // Scale
736 if (empty($scalegrades[$this->assignment->id])) {
737 if ($scale = get_record('scale', 'id', -($this->assignment->grade))) {
738 $scalegrades[$this->assignment->id] = make_menu_from_list($scale->scale);
739 } else {
740 return '-';
743 if (isset($scalegrades[$this->assignment->id][$grade])) {
744 return $scalegrades[$this->assignment->id][$grade];
746 return '-';
751 * Display a single submission, ready for grading on a popup window
753 * This default method prints the teacher info and submissioncomment box at the top and
754 * the student info and submission at the bottom.
755 * This method also fetches the necessary data in order to be able to
756 * provide a "Next submission" button.
757 * Calls preprocess_submission() to give assignment type plug-ins a chance
758 * to process submissions before they are graded
759 * This method gets its arguments from the page parameters userid and offset
761 function display_submission($extra_javascript = '') {
763 global $CFG;
764 require_once($CFG->libdir.'/gradelib.php');
765 require_once($CFG->libdir.'/tablelib.php');
767 $userid = required_param('userid', PARAM_INT);
768 $offset = required_param('offset', PARAM_INT);//offset for where to start looking for student.
770 if (!$user = get_record('user', 'id', $userid)) {
771 error('No such user!');
774 if (!$submission = $this->get_submission($user->id)) {
775 $submission = $this->prepare_new_submission($userid);
777 if ($submission->timemodified > $submission->timemarked) {
778 $subtype = 'assignmentnew';
779 } else {
780 $subtype = 'assignmentold';
783 $grading_info = grade_get_grades($this->course->id, 'mod', 'assignment', $this->assignment->id, array($user->id));
784 $disabled = $grading_info->items[0]->grades[$userid]->locked || $grading_info->items[0]->grades[$userid]->overridden;
786 /// construct SQL, using current offset to find the data of the next student
787 $course = $this->course;
788 $assignment = $this->assignment;
789 $cm = $this->cm;
790 $context = get_context_instance(CONTEXT_MODULE, $cm->id);
792 /// Get all ppl that can submit assignments
794 $currentgroup = groups_get_activity_group($cm);
795 if ($users = get_users_by_capability($context, 'mod/assignment:submit', 'u.id', '', '', '', $currentgroup, '', false)) {
796 $users = array_keys($users);
799 // if groupmembersonly used, remove users who are not in any group
800 if ($users and !empty($CFG->enablegroupings) and $cm->groupmembersonly) {
801 if ($groupingusers = groups_get_grouping_members($cm->groupingid, 'u.id', 'u.id')) {
802 $users = array_intersect($users, array_keys($groupingusers));
806 $nextid = 0;
808 if ($users) {
809 $select = 'SELECT u.id, u.firstname, u.lastname, u.picture, u.imagealt,
810 s.id AS submissionid, s.grade, s.submissioncomment,
811 s.timemodified, s.timemarked,
812 COALESCE(SIGN(SIGN(s.timemarked) + SIGN(s.timemarked - s.timemodified)), 0) AS status ';
813 $sql = 'FROM '.$CFG->prefix.'user u '.
814 'LEFT JOIN '.$CFG->prefix.'assignment_submissions s ON u.id = s.userid
815 AND s.assignment = '.$this->assignment->id.' '.
816 'WHERE u.id IN ('.implode(',', $users).') ';
818 if ($sort = flexible_table::get_sql_sort('mod-assignment-submissions')) {
819 $sort = 'ORDER BY '.$sort.' ';
822 if (($auser = get_records_sql($select.$sql.$sort, $offset+1, 1)) !== false) {
823 $nextuser = array_shift($auser);
824 /// Calculate user status
825 $nextuser->status = ($nextuser->timemarked > 0) && ($nextuser->timemarked >= $nextuser->timemodified);
826 $nextid = $nextuser->id;
830 print_header(get_string('feedback', 'assignment').':'.fullname($user, true).':'.format_string($this->assignment->name));
832 /// Print any extra javascript needed for saveandnext
833 echo $extra_javascript;
835 ///SOme javascript to help with setting up >.>
837 echo '<script type="text/javascript">'."\n";
838 echo 'function setNext(){'."\n";
839 echo 'document.getElementById(\'submitform\').mode.value=\'next\';'."\n";
840 echo 'document.getElementById(\'submitform\').userid.value="'.$nextid.'";'."\n";
841 echo '}'."\n";
843 echo 'function saveNext(){'."\n";
844 echo 'document.getElementById(\'submitform\').mode.value=\'saveandnext\';'."\n";
845 echo 'document.getElementById(\'submitform\').userid.value="'.$nextid.'";'."\n";
846 echo 'document.getElementById(\'submitform\').saveuserid.value="'.$userid.'";'."\n";
847 echo 'document.getElementById(\'submitform\').menuindex.value = document.getElementById(\'submitform\').grade.selectedIndex;'."\n";
848 echo '}'."\n";
850 echo '</script>'."\n";
851 echo '<table cellspacing="0" class="feedback '.$subtype.'" >';
853 ///Start of teacher info row
855 echo '<tr>';
856 echo '<td class="picture teacher">';
857 if ($submission->teacher) {
858 $teacher = get_record('user', 'id', $submission->teacher);
859 } else {
860 global $USER;
861 $teacher = $USER;
863 print_user_picture($teacher, $this->course->id, $teacher->picture);
864 echo '</td>';
865 echo '<td class="content">';
866 echo '<form id="submitform" action="submissions.php" method="post">';
867 echo '<div>'; // xhtml compatibility - invisiblefieldset was breaking layout here
868 echo '<input type="hidden" name="offset" value="'.($offset+1).'" />';
869 echo '<input type="hidden" name="userid" value="'.$userid.'" />';
870 echo '<input type="hidden" name="id" value="'.$this->cm->id.'" />';
871 echo '<input type="hidden" name="mode" value="grade" />';
872 echo '<input type="hidden" name="menuindex" value="0" />';//selected menu index
874 //new hidden field, initialized to -1.
875 echo '<input type="hidden" name="saveuserid" value="-1" />';
877 if ($submission->timemarked) {
878 echo '<div class="from">';
879 echo '<div class="fullname">'.fullname($teacher, true).'</div>';
880 echo '<div class="time">'.userdate($submission->timemarked).'</div>';
881 echo '</div>';
883 echo '<div class="grade"><label for="menugrade">'.get_string('grade').'</label> ';
884 choose_from_menu(make_grades_menu($this->assignment->grade), 'grade', $submission->grade, get_string('nograde'), '', -1, false, $disabled);
885 echo '</div>';
887 echo '<div class="clearer"></div>';
888 echo '<div class="finalgrade">'.get_string('finalgrade', 'grades').': '.$grading_info->items[0]->grades[$userid]->str_grade.'</div>';
889 echo '<div class="clearer"></div>';
891 if (!empty($CFG->enableoutcomes)) {
892 foreach($grading_info->outcomes as $n=>$outcome) {
893 echo '<div class="outcome"><label for="menuoutcome_'.$n.'">'.$outcome->name.'</label> ';
894 $options = make_grades_menu(-$outcome->scaleid);
895 if ($outcome->grades[$submission->userid]->locked) {
896 $options[0] = get_string('nooutcome', 'grades');
897 echo $options[$outcome->grades[$submission->userid]->grade];
898 } else {
899 choose_from_menu($options, 'outcome_'.$n.'['.$userid.']', $outcome->grades[$submission->userid]->grade, get_string('nooutcome', 'grades'), '', 0, false, false, 0, 'menuoutcome_'.$n);
901 echo '</div>';
902 echo '<div class="clearer"></div>';
907 $this->preprocess_submission($submission);
909 if ($disabled) {
910 echo '<div class="disabledfeedback">'.$grading_info->items[0]->grades[$userid]->str_feedback.'</div>';
912 } else {
913 print_textarea($this->usehtmleditor, 14, 58, 0, 0, 'submissioncomment', $submission->submissioncomment, $this->course->id);
914 if ($this->usehtmleditor) {
915 echo '<input type="hidden" name="format" value="'.FORMAT_HTML.'" />';
916 } else {
917 echo '<div class="format">';
918 choose_from_menu(format_text_menu(), "format", $submission->format, "");
919 helpbutton("textformat", get_string("helpformatting"));
920 echo '</div>';
924 ///Print Buttons in Single View
925 echo '<div class="buttons">';
926 echo '<input type="submit" name="submit" value="'.get_string('savechanges').'" onclick = "document.getElementById(\'submitform\').menuindex.value = document.getElementById(\'submitform\').grade.selectedIndex" />';
927 echo '<input type="submit" name="cancel" value="'.get_string('cancel').'" />';
928 //if there are more to be graded.
929 if ($nextid) {
930 echo '<input type="submit" name="saveandnext" value="'.get_string('saveandnext').'" onclick="saveNext()" />';
931 echo '<input type="submit" name="next" value="'.get_string('next').'" onclick="setNext();" />';
933 echo '</div>';
934 echo '</div></form>';
936 $customfeedback = $this->custom_feedbackform($submission, true);
937 if (!empty($customfeedback)) {
938 echo $customfeedback;
941 echo '</td></tr>';
943 ///End of teacher info row, Start of student info row
944 echo '<tr>';
945 echo '<td class="picture user">';
946 print_user_picture($user, $this->course->id, $user->picture);
947 echo '</td>';
948 echo '<td class="topic">';
949 echo '<div class="from">';
950 echo '<div class="fullname">'.fullname($user, true).'</div>';
951 if ($submission->timemodified) {
952 echo '<div class="time">'.userdate($submission->timemodified).
953 $this->display_lateness($submission->timemodified).'</div>';
955 echo '</div>';
956 $this->print_user_files($user->id);
957 echo '</td>';
958 echo '</tr>';
960 ///End of student info row
962 echo '</table>';
964 if (!$disabled and $this->usehtmleditor) {
965 use_html_editor();
968 print_footer('none');
972 * Preprocess submission before grading
974 * Called by display_submission()
975 * The default type does nothing here.
976 * @param $submission object The submission object
978 function preprocess_submission(&$submission) {
982 * Display all the submissions ready for grading
984 function display_submissions($message='') {
985 global $CFG, $db, $USER;
986 require_once($CFG->libdir.'/gradelib.php');
988 /* first we check to see if the form has just been submitted
989 * to request user_preference updates
992 if (isset($_POST['updatepref'])){
993 $perpage = optional_param('perpage', 10, PARAM_INT);
994 $perpage = ($perpage <= 0) ? 10 : $perpage ;
995 set_user_preference('assignment_perpage', $perpage);
996 set_user_preference('assignment_quickgrade', optional_param('quickgrade',0, PARAM_BOOL));
999 /* next we get perpage and quickgrade (allow quick grade) params
1000 * from database
1002 $perpage = get_user_preferences('assignment_perpage', 10);
1004 $quickgrade = get_user_preferences('assignment_quickgrade', 0);
1006 $grading_info = grade_get_grades($this->course->id, 'mod', 'assignment', $this->assignment->id);
1008 if (!empty($CFG->enableoutcomes) and !empty($grading_info->outcomes)) {
1009 $uses_outcomes = true;
1010 } else {
1011 $uses_outcomes = false;
1014 $page = optional_param('page', 0, PARAM_INT);
1015 $strsaveallfeedback = get_string('saveallfeedback', 'assignment');
1017 /// Some shortcuts to make the code read better
1019 $course = $this->course;
1020 $assignment = $this->assignment;
1021 $cm = $this->cm;
1023 $tabindex = 1; //tabindex for quick grading tabbing; Not working for dropdowns yet
1025 add_to_log($course->id, 'assignment', 'view submission', 'submissions.php?id='.$this->assignment->id, $this->assignment->id, $this->cm->id);
1027 $navigation = build_navigation($this->strsubmissions, $this->cm);
1028 print_header_simple(format_string($this->assignment->name,true), "", $navigation,
1029 '', '', true, update_module_button($cm->id, $course->id, $this->strassignment), navmenu($course, $cm));
1031 $course_context = get_context_instance(CONTEXT_COURSE, $course->id);
1032 if (has_capability('gradereport/grader:view', $course_context) && has_capability('moodle/grade:viewall', $course_context)) {
1033 echo '<a class="allcoursegrades" href="' . $CFG->wwwroot . '/grade/report/grader/index.php?id=' . $course->id . '">'
1034 . get_string('seeallcoursegrades', 'grades') . '</a>';
1037 if (!empty($message)) {
1038 echo $message; // display messages here if any
1041 $context = get_context_instance(CONTEXT_MODULE, $cm->id);
1043 /// Check to see if groups are being used in this assignment
1045 /// find out current groups mode
1046 $groupmode = groups_get_activity_groupmode($cm);
1047 $currentgroup = groups_get_activity_group($cm, true);
1048 groups_print_activity_menu($cm, 'submissions.php?id=' . $this->cm->id);
1050 /// Get all ppl that are allowed to submit assignments
1051 if ($users = get_users_by_capability($context, 'mod/assignment:submit', 'u.id', '', '', '', $currentgroup, '', false)) {
1052 $users = array_keys($users);
1055 // if groupmembersonly used, remove users who are not in any group
1056 if ($users and !empty($CFG->enablegroupings) and $cm->groupmembersonly) {
1057 if ($groupingusers = groups_get_grouping_members($cm->groupingid, 'u.id', 'u.id')) {
1058 $users = array_intersect($users, array_keys($groupingusers));
1062 $tablecolumns = array('picture', 'fullname', 'grade', 'submissioncomment', 'timemodified', 'timemarked', 'status', 'finalgrade');
1063 if ($uses_outcomes) {
1064 $tablecolumns[] = 'outcome'; // no sorting based on outcomes column
1067 $tableheaders = array('',
1068 get_string('fullname'),
1069 get_string('grade'),
1070 get_string('comment', 'assignment'),
1071 get_string('lastmodified').' ('.$course->student.')',
1072 get_string('lastmodified').' ('.$course->teacher.')',
1073 get_string('status'),
1074 get_string('finalgrade', 'grades'));
1075 if ($uses_outcomes) {
1076 $tableheaders[] = get_string('outcome', 'grades');
1079 require_once($CFG->libdir.'/tablelib.php');
1080 $table = new flexible_table('mod-assignment-submissions');
1082 $table->define_columns($tablecolumns);
1083 $table->define_headers($tableheaders);
1084 $table->define_baseurl($CFG->wwwroot.'/mod/assignment/submissions.php?id='.$this->cm->id.'&amp;currentgroup='.$currentgroup);
1086 $table->sortable(true, 'lastname');//sorted by lastname by default
1087 $table->collapsible(true);
1088 $table->initialbars(true);
1090 $table->column_suppress('picture');
1091 $table->column_suppress('fullname');
1093 $table->column_class('picture', 'picture');
1094 $table->column_class('fullname', 'fullname');
1095 $table->column_class('grade', 'grade');
1096 $table->column_class('submissioncomment', 'comment');
1097 $table->column_class('timemodified', 'timemodified');
1098 $table->column_class('timemarked', 'timemarked');
1099 $table->column_class('status', 'status');
1100 $table->column_class('finalgrade', 'finalgrade');
1101 if ($uses_outcomes) {
1102 $table->column_class('outcome', 'outcome');
1105 $table->set_attribute('cellspacing', '0');
1106 $table->set_attribute('id', 'attempts');
1107 $table->set_attribute('class', 'submissions');
1108 $table->set_attribute('width', '90%');
1109 //$table->set_attribute('align', 'center');
1111 $table->no_sorting('finalgrade');
1112 $table->no_sorting('outcome');
1114 // Start working -- this is necessary as soon as the niceties are over
1115 $table->setup();
1117 if (empty($users)) {
1118 print_heading(get_string('nosubmitusers','assignment'));
1119 return true;
1122 /// Construct the SQL
1124 if ($where = $table->get_sql_where()) {
1125 $where .= ' AND ';
1128 if ($sort = $table->get_sql_sort()) {
1129 $sort = ' ORDER BY '.$sort;
1132 $select = 'SELECT u.id, u.firstname, u.lastname, u.picture, u.imagealt,
1133 s.id AS submissionid, s.grade, s.submissioncomment,
1134 s.timemodified, s.timemarked,
1135 COALESCE(SIGN(SIGN(s.timemarked) + SIGN(s.timemarked - s.timemodified)), 0) AS status ';
1136 $sql = 'FROM '.$CFG->prefix.'user u '.
1137 'LEFT JOIN '.$CFG->prefix.'assignment_submissions s ON u.id = s.userid
1138 AND s.assignment = '.$this->assignment->id.' '.
1139 'WHERE '.$where.'u.id IN ('.implode(',',$users).') ';
1141 $table->pagesize($perpage, count($users));
1143 ///offset used to calculate index of student in that particular query, needed for the pop up to know who's next
1144 $offset = $page * $perpage;
1146 $strupdate = get_string('update');
1147 $strgrade = get_string('grade');
1148 $grademenu = make_grades_menu($this->assignment->grade);
1150 if (($ausers = get_records_sql($select.$sql.$sort, $table->get_page_start(), $table->get_page_size())) !== false) {
1151 $grading_info = grade_get_grades($this->course->id, 'mod', 'assignment', $this->assignment->id, array_keys($ausers));
1152 foreach ($ausers as $auser) {
1153 $final_grade = $grading_info->items[0]->grades[$auser->id];
1154 /// Calculate user status
1155 $auser->status = ($auser->timemarked > 0) && ($auser->timemarked >= $auser->timemodified);
1156 $picture = print_user_picture($auser, $course->id, $auser->picture, false, true);
1158 if (empty($auser->submissionid)) {
1159 $auser->grade = -1; //no submission yet
1162 if (!empty($auser->submissionid)) {
1163 ///Prints student answer and student modified date
1164 ///attach file or print link to student answer, depending on the type of the assignment.
1165 ///Refer to print_student_answer in inherited classes.
1166 if ($auser->timemodified > 0) {
1167 $studentmodified = '<div id="ts'.$auser->id.'">'.$this->print_student_answer($auser->id)
1168 . userdate($auser->timemodified).'</div>';
1169 } else {
1170 $studentmodified = '<div id="ts'.$auser->id.'">&nbsp;</div>';
1172 ///Print grade, dropdown or text
1173 if ($auser->timemarked > 0) {
1174 $teachermodified = '<div id="tt'.$auser->id.'">'.userdate($auser->timemarked).'</div>';
1176 if ($final_grade->locked or $final_grade->overridden) {
1177 $grade = '<div id="g'.$auser->id.'">'.$final_grade->str_grade.'</div>';
1178 } else if ($quickgrade) {
1179 $menu = choose_from_menu(make_grades_menu($this->assignment->grade),
1180 'menu['.$auser->id.']', $auser->grade,
1181 get_string('nograde'),'',-1,true,false,$tabindex++);
1182 $grade = '<div id="g'.$auser->id.'">'. $menu .'</div>';
1183 } else {
1184 $grade = '<div id="g'.$auser->id.'">'.$this->display_grade($auser->grade).'</div>';
1187 } else {
1188 $teachermodified = '<div id="tt'.$auser->id.'">&nbsp;</div>';
1189 if ($final_grade->locked or $final_grade->overridden) {
1190 $grade = '<div id="g'.$auser->id.'">'.$final_grade->str_grade.'</div>';
1191 } else if ($quickgrade) {
1192 $menu = choose_from_menu(make_grades_menu($this->assignment->grade),
1193 'menu['.$auser->id.']', $auser->grade,
1194 get_string('nograde'),'',-1,true,false,$tabindex++);
1195 $grade = '<div id="g'.$auser->id.'">'.$menu.'</div>';
1196 } else {
1197 $grade = '<div id="g'.$auser->id.'">'.$this->display_grade($auser->grade).'</div>';
1200 ///Print Comment
1201 if ($final_grade->locked or $final_grade->overridden) {
1202 $comment = '<div id="com'.$auser->id.'">'.shorten_text(strip_tags($final_grade->str_feedback),15).'</div>';
1204 } else if ($quickgrade) {
1205 $comment = '<div id="com'.$auser->id.'">'
1206 . '<textarea tabindex="'.$tabindex++.'" name="submissioncomment['.$auser->id.']" id="submissioncomment'
1207 . $auser->id.'" rows="2" cols="20">'.($auser->submissioncomment).'</textarea></div>';
1208 } else {
1209 $comment = '<div id="com'.$auser->id.'">'.shorten_text(strip_tags($auser->submissioncomment),15).'</div>';
1211 } else {
1212 $studentmodified = '<div id="ts'.$auser->id.'">&nbsp;</div>';
1213 $teachermodified = '<div id="tt'.$auser->id.'">&nbsp;</div>';
1214 $status = '<div id="st'.$auser->id.'">&nbsp;</div>';
1216 if ($final_grade->locked or $final_grade->overridden) {
1217 $grade = '<div id="g'.$auser->id.'">'.$final_grade->str_grade.'</div>';
1218 } else if ($quickgrade) { // allow editing
1219 $menu = choose_from_menu(make_grades_menu($this->assignment->grade),
1220 'menu['.$auser->id.']', $auser->grade,
1221 get_string('nograde'),'',-1,true,false,$tabindex++);
1222 $grade = '<div id="g'.$auser->id.'">'.$menu.'</div>';
1223 } else {
1224 $grade = '<div id="g'.$auser->id.'">-</div>';
1227 if ($final_grade->locked or $final_grade->overridden) {
1228 $comment = '<div id="com'.$auser->id.'">'.$final_grade->str_feedback.'</div>';
1229 } else if ($quickgrade) {
1230 $comment = '<div id="com'.$auser->id.'">'
1231 . '<textarea tabindex="'.$tabindex++.'" name="submissioncomment['.$auser->id.']" id="submissioncomment'
1232 . $auser->id.'" rows="2" cols="20">'.($auser->submissioncomment).'</textarea></div>';
1233 } else {
1234 $comment = '<div id="com'.$auser->id.'">&nbsp;</div>';
1238 if (empty($auser->status)) { /// Confirm we have exclusively 0 or 1
1239 $auser->status = 0;
1240 } else {
1241 $auser->status = 1;
1244 $buttontext = ($auser->status == 1) ? $strupdate : $strgrade;
1246 ///No more buttons, we use popups ;-).
1247 $popup_url = '/mod/assignment/submissions.php?id='.$this->cm->id
1248 . '&amp;userid='.$auser->id.'&amp;mode=single'.'&amp;offset='.$offset++;
1249 $button = link_to_popup_window ($popup_url, 'grade'.$auser->id, $buttontext, 600, 780,
1250 $buttontext, 'none', true, 'button'.$auser->id);
1252 $status = '<div id="up'.$auser->id.'" class="s'.$auser->status.'">'.$button.'</div>';
1254 $finalgrade = '<span id="finalgrade_'.$auser->id.'">'.$final_grade->str_grade.'</span>';
1256 $outcomes = '';
1258 if ($uses_outcomes) {
1260 foreach($grading_info->outcomes as $n=>$outcome) {
1261 $outcomes .= '<div class="outcome"><label>'.$outcome->name.'</label>';
1262 $options = make_grades_menu(-$outcome->scaleid);
1264 if ($outcome->grades[$auser->id]->locked or !$quickgrade) {
1265 $options[0] = get_string('nooutcome', 'grades');
1266 $outcomes .= ': <span id="outcome_'.$n.'_'.$auser->id.'">'.$options[$outcome->grades[$auser->id]->grade].'</span>';
1267 } else {
1268 $outcomes .= ' ';
1269 $outcomes .= choose_from_menu($options, 'outcome_'.$n.'['.$auser->id.']',
1270 $outcome->grades[$auser->id]->grade, get_string('nooutcome', 'grades'), '', 0, true, false, 0, 'outcome_'.$n.'_'.$auser->id);
1272 $outcomes .= '</div>';
1277 $row = array($picture, fullname($auser), $grade, $comment, $studentmodified, $teachermodified, $status, $finalgrade);
1278 if ($uses_outcomes) {
1279 $row[] = $outcomes;
1282 $table->add_data($row);
1286 /// Print quickgrade form around the table
1287 if ($quickgrade){
1288 echo '<form action="submissions.php" id="fastg" method="post">';
1289 echo '<div>';
1290 echo '<input type="hidden" name="id" value="'.$this->cm->id.'" />';
1291 echo '<input type="hidden" name="mode" value="fastgrade" />';
1292 echo '<input type="hidden" name="page" value="'.$page.'" />';
1293 echo '</div>';
1294 //echo '<div style="text-align:center"><input type="submit" name="fastg" value="'.get_string('saveallfeedback', 'assignment').'" /></div>';
1297 $table->print_html(); /// Print the whole table
1299 if ($quickgrade){
1300 echo '<div style="text-align:center"><input type="submit" name="fastg" value="'.get_string('saveallfeedback', 'assignment').'" /></div>';
1301 echo '</form>';
1303 /// End of fast grading form
1305 /// Mini form for setting user preference
1306 echo '<br />';
1307 echo '<form id="options" action="submissions.php?id='.$this->cm->id.'" method="post">';
1308 echo '<div>';
1309 echo '<input type="hidden" id="updatepref" name="updatepref" value="1" />';
1310 echo '<table id="optiontable" align="right">';
1311 echo '<tr align="right"><td>';
1312 echo '<label for="perpage">'.get_string('pagesize','assignment').'</label>';
1313 echo ':</td>';
1314 echo '<td>';
1315 echo '<input type="text" id="perpage" name="perpage" size="1" value="'.$perpage.'" />';
1316 helpbutton('pagesize', get_string('pagesize','assignment'), 'assignment');
1317 echo '</td></tr>';
1318 echo '<tr align="right">';
1319 echo '<td>';
1320 print_string('quickgrade','assignment');
1321 echo ':</td>';
1322 echo '<td>';
1323 if ($quickgrade){
1324 echo '<input type="checkbox" name="quickgrade" value="1" checked="checked" />';
1325 } else {
1326 echo '<input type="checkbox" name="quickgrade" value="1" />';
1328 helpbutton('quickgrade', get_string('quickgrade', 'assignment'), 'assignment').'</p></div>';
1329 echo '</td></tr>';
1330 echo '<tr>';
1331 echo '<td colspan="2" align="right">';
1332 echo '<input type="submit" value="'.get_string('savepreferences').'" />';
1333 echo '</td></tr></table>';
1334 echo '</div>';
1335 echo '</form>';
1336 ///End of mini form
1337 print_footer($this->course);
1341 * Process teacher feedback submission
1343 * This is called by submissions() when a grading even has taken place.
1344 * It gets its data from the submitted form.
1345 * @return object The updated submission object
1347 function process_feedback() {
1348 global $CFG, $USER;
1349 require_once($CFG->libdir.'/gradelib.php');
1351 if (!$feedback = data_submitted()) { // No incoming data?
1352 return false;
1355 ///For save and next, we need to know the userid to save, and the userid to go
1356 ///We use a new hidden field in the form, and set it to -1. If it's set, we use this
1357 ///as the userid to store
1358 if ((int)$feedback->saveuserid !== -1){
1359 $feedback->userid = $feedback->saveuserid;
1362 if (!empty($feedback->cancel)) { // User hit cancel button
1363 return false;
1366 $grading_info = grade_get_grades($this->course->id, 'mod', 'assignment', $this->assignment->id, $feedback->userid);
1368 // store outcomes if needed
1369 $this->process_outcomes($feedback->userid);
1371 $submission = $this->get_submission($feedback->userid, true); // Get or make one
1373 if (!$grading_info->items[0]->grades[$feedback->userid]->locked and
1374 !$grading_info->items[0]->grades[$feedback->userid]->overridden) {
1376 $submission->grade = $feedback->grade;
1377 $submission->submissioncomment = $feedback->submissioncomment;
1378 $submission->format = $feedback->format;
1379 $submission->teacher = $USER->id;
1380 $submission->mailed = 0; // Make sure mail goes out (again, even)
1381 $submission->timemarked = time();
1383 unset($submission->data1); // Don't need to update this.
1384 unset($submission->data2); // Don't need to update this.
1386 if (empty($submission->timemodified)) { // eg for offline assignments
1387 // $submission->timemodified = time();
1390 if (! update_record('assignment_submissions', $submission)) {
1391 return false;
1394 // triger grade event
1395 $this->update_grade($submission);
1397 add_to_log($this->course->id, 'assignment', 'update grades',
1398 'submissions.php?id='.$this->assignment->id.'&user='.$feedback->userid, $feedback->userid, $this->cm->id);
1401 return $submission;
1405 function process_outcomes($userid) {
1406 global $CFG, $USER;
1408 if (empty($CFG->enableoutcomes)) {
1409 return;
1412 require_once($CFG->libdir.'/gradelib.php');
1414 if (!$formdata = data_submitted()) {
1415 return;
1418 $data = array();
1419 $grading_info = grade_get_grades($this->course->id, 'mod', 'assignment', $this->assignment->id, $userid);
1421 if (!empty($grading_info->outcomes)) {
1422 foreach($grading_info->outcomes as $n=>$old) {
1423 $name = 'outcome_'.$n;
1424 if (isset($formdata->{$name}[$userid]) and $old->grades[$userid]->grade != $formdata->{$name}[$userid]) {
1425 $data[$n] = $formdata->{$name}[$userid];
1429 if (count($data) > 0) {
1430 grade_update_outcomes('mod/assignment', $this->course->id, 'mod', 'assignment', $this->assignment->id, $userid, $data);
1436 * Load the submission object for a particular user
1438 * @param $userid int The id of the user whose submission we want or 0 in which case USER->id is used
1439 * @param $createnew boolean optional Defaults to false. If set to true a new submission object will be created in the database
1440 * @return object The submission
1442 function get_submission($userid=0, $createnew=false) {
1443 global $USER;
1445 if (empty($userid)) {
1446 $userid = $USER->id;
1449 $submission = get_record('assignment_submissions', 'assignment', $this->assignment->id, 'userid', $userid);
1451 if ($submission || !$createnew) {
1452 return $submission;
1454 $newsubmission = $this->prepare_new_submission($userid);
1455 if (!insert_record("assignment_submissions", $newsubmission)) {
1456 error("Could not insert a new empty submission");
1459 return get_record('assignment_submissions', 'assignment', $this->assignment->id, 'userid', $userid);
1463 * Instantiates a new submission object for a given user
1465 * Sets the assignment, userid and times, everything else is set to default values.
1466 * @param $userid int The userid for which we want a submission object
1467 * @return object The submission
1469 function prepare_new_submission($userid) {
1470 $submission = new Object;
1471 $submission->assignment = $this->assignment->id;
1472 $submission->userid = $userid;
1473 //$submission->timecreated = time();
1474 $submission->timecreated = '';
1475 // teachers should not be modifying modified date, except offline assignments
1476 $submission->timemodified = $submission->timecreated;
1477 $submission->numfiles = 0;
1478 $submission->data1 = '';
1479 $submission->data2 = '';
1480 $submission->grade = -1;
1481 $submission->submissioncomment = '';
1482 $submission->format = 0;
1483 $submission->teacher = 0;
1484 $submission->timemarked = 0;
1485 $submission->mailed = 0;
1486 return $submission;
1490 * Return all assignment submissions by ENROLLED students (even empty)
1492 * @param $sort string optional field names for the ORDER BY in the sql query
1493 * @param $dir string optional specifying the sort direction, defaults to DESC
1494 * @return array The submission objects indexed by id
1496 function get_submissions($sort='', $dir='DESC') {
1497 return assignment_get_all_submissions($this->assignment, $sort, $dir);
1501 * Counts all real assignment submissions by ENROLLED students (not empty ones)
1503 * @param $groupid int optional If nonzero then count is restricted to this group
1504 * @return int The number of submissions
1506 function count_real_submissions($groupid=0) {
1507 return assignment_count_real_submissions($this->cm, $groupid);
1511 * Alerts teachers by email of new or changed assignments that need grading
1513 * First checks whether the option to email teachers is set for this assignment.
1514 * Sends an email to ALL teachers in the course (or in the group if using separate groups).
1515 * Uses the methods email_teachers_text() and email_teachers_html() to construct the content.
1516 * @param $submission object The submission that has changed
1518 function email_teachers($submission) {
1519 global $CFG;
1521 if (empty($this->assignment->emailteachers)) { // No need to do anything
1522 return;
1525 $user = get_record('user', 'id', $submission->userid);
1527 if ($teachers = $this->get_graders($user)) {
1529 $strassignments = get_string('modulenameplural', 'assignment');
1530 $strassignment = get_string('modulename', 'assignment');
1531 $strsubmitted = get_string('submitted', 'assignment');
1533 foreach ($teachers as $teacher) {
1534 $info = new object();
1535 $info->username = fullname($user, true);
1536 $info->assignment = format_string($this->assignment->name,true);
1537 $info->url = $CFG->wwwroot.'/mod/assignment/submissions.php?id='.$this->cm->id;
1539 $postsubject = $strsubmitted.': '.$info->username.' -> '.$this->assignment->name;
1540 $posttext = $this->email_teachers_text($info);
1541 $posthtml = ($teacher->mailformat == 1) ? $this->email_teachers_html($info) : '';
1543 @email_to_user($teacher, $user, $postsubject, $posttext, $posthtml); // If it fails, oh well, too bad.
1549 * Returns a list of teachers that should be grading given submission
1551 function get_graders($user) {
1552 //potential graders
1553 $potgraders = get_users_by_capability($this->context, 'mod/assignment:grade', '', '', '', '', '', '', false, false);
1555 $graders = array();
1556 if (groups_get_activity_groupmode($this->cm) == SEPARATEGROUPS) { // Separate groups are being used
1557 if ($groups = groups_get_all_groups($this->course->id, $user->id)) { // Try to find all groups
1558 foreach ($groups as $group) {
1559 foreach ($potgraders as $t) {
1560 if ($t->id == $user->id) {
1561 continue; // do not send self
1563 if (groups_is_member($group->id, $t->id)) {
1564 $graders[$t->id] = $t;
1568 } else {
1569 // user not in group, try to find graders without group
1570 foreach ($potgraders as $t) {
1571 if ($t->id == $user->id) {
1572 continue; // do not send self
1574 if (!groups_get_all_groups($this->course->id, $t->id)) { //ugly hack
1575 $graders[$t->id] = $t;
1579 } else {
1580 foreach ($potgraders as $t) {
1581 if ($t->id == $user->id) {
1582 continue; // do not send self
1584 $graders[$t->id] = $t;
1587 return $graders;
1591 * Creates the text content for emails to teachers
1593 * @param $info object The info used by the 'emailteachermail' language string
1594 * @return string
1596 function email_teachers_text($info) {
1597 $posttext = format_string($this->course->shortname).' -> '.$this->strassignments.' -> '.
1598 format_string($this->assignment->name)."\n";
1599 $posttext .= '---------------------------------------------------------------------'."\n";
1600 $posttext .= get_string("emailteachermail", "assignment", $info)."\n";
1601 $posttext .= "\n---------------------------------------------------------------------\n";
1602 return $posttext;
1606 * Creates the html content for emails to teachers
1608 * @param $info object The info used by the 'emailteachermailhtml' language string
1609 * @return string
1611 function email_teachers_html($info) {
1612 global $CFG;
1613 $posthtml = '<p><font face="sans-serif">'.
1614 '<a href="'.$CFG->wwwroot.'/course/view.php?id='.$this->course->id.'">'.format_string($this->course->shortname).'</a> ->'.
1615 '<a href="'.$CFG->wwwroot.'/mod/assignment/index.php?id='.$this->course->id.'">'.$this->strassignments.'</a> ->'.
1616 '<a href="'.$CFG->wwwroot.'/mod/assignment/view.php?id='.$this->cm->id.'">'.format_string($this->assignment->name).'</a></font></p>';
1617 $posthtml .= '<hr /><font face="sans-serif">';
1618 $posthtml .= '<p>'.get_string('emailteachermailhtml', 'assignment', $info).'</p>';
1619 $posthtml .= '</font><hr />';
1620 return $posthtml;
1624 * Produces a list of links to the files uploaded by a user
1626 * @param $userid int optional id of the user. If 0 then $USER->id is used.
1627 * @param $return boolean optional defaults to false. If true the list is returned rather than printed
1628 * @return string optional
1630 function print_user_files($userid=0, $return=false) {
1631 global $CFG, $USER;
1633 if (!$userid) {
1634 if (!isloggedin()) {
1635 return '';
1637 $userid = $USER->id;
1640 $filearea = $this->file_area_name($userid);
1642 $output = '';
1644 if ($basedir = $this->file_area($userid)) {
1645 if ($files = get_directory_list($basedir)) {
1646 require_once($CFG->libdir.'/filelib.php');
1647 foreach ($files as $key => $file) {
1649 $icon = mimeinfo('icon', $file);
1651 if ($CFG->slasharguments) {
1652 $ffurl = "$CFG->wwwroot/file.php/$filearea/$file";
1653 } else {
1654 $ffurl = "$CFG->wwwroot/file.php?file=/$filearea/$file";
1657 $output .= '<img align="middle" src="'.$CFG->pixpath.'/f/'.$icon.'" class="icon" alt="'.$icon.'" />'.
1658 '<a href="'.$ffurl.'" >'.$file.'</a><br />';
1663 $output = '<div class="files">'.$output.'</div>';
1665 if ($return) {
1666 return $output;
1668 echo $output;
1672 * Count the files uploaded by a given user
1674 * @param $userid int The user id
1675 * @return int
1677 function count_user_files($userid) {
1678 global $CFG;
1680 $filearea = $this->file_area_name($userid);
1682 if ( is_dir($CFG->dataroot.'/'.$filearea) && $basedir = $this->file_area($userid)) {
1683 if ($files = get_directory_list($basedir)) {
1684 return count($files);
1687 return 0;
1691 * Creates a directory file name, suitable for make_upload_directory()
1693 * @param $userid int The user id
1694 * @return string path to file area
1696 function file_area_name($userid) {
1697 global $CFG;
1699 return $this->course->id.'/'.$CFG->moddata.'/assignment/'.$this->assignment->id.'/'.$userid;
1703 * Makes an upload directory
1705 * @param $userid int The user id
1706 * @return string path to file area.
1708 function file_area($userid) {
1709 return make_upload_directory( $this->file_area_name($userid) );
1713 * Returns true if the student is allowed to submit
1715 * Checks that the assignment has started and, if the option to prevent late
1716 * submissions is set, also checks that the assignment has not yet closed.
1717 * @return boolean
1719 function isopen() {
1720 $time = time();
1721 if ($this->assignment->preventlate && $this->assignment->timedue) {
1722 return ($this->assignment->timeavailable <= $time && $time <= $this->assignment->timedue);
1723 } else {
1724 return ($this->assignment->timeavailable <= $time);
1730 * Return true if is set description is hidden till available date
1732 * This is needed by calendar so that hidden descriptions do not
1733 * come up in upcoming events.
1735 * Check that description is hidden till available date
1736 * By default return false
1737 * Assignments types should implement this method if needed
1738 * @return boolen
1740 function description_is_hidden() {
1741 return false;
1745 * Return an outline of the user's interaction with the assignment
1747 * The default method prints the grade and timemodified
1748 * @param $user object
1749 * @return object with properties ->info and ->time
1751 function user_outline($user) {
1752 if ($submission = $this->get_submission($user->id)) {
1754 $result = new object();
1755 $result->info = get_string('grade').': '.$this->display_grade($submission->grade);
1756 $result->time = $submission->timemodified;
1757 return $result;
1759 return NULL;
1763 * Print complete information about the user's interaction with the assignment
1765 * @param $user object
1767 function user_complete($user) {
1768 if ($submission = $this->get_submission($user->id)) {
1769 if ($basedir = $this->file_area($user->id)) {
1770 if ($files = get_directory_list($basedir)) {
1771 $countfiles = count($files)." ".get_string("uploadedfiles", "assignment");
1772 foreach ($files as $file) {
1773 $countfiles .= "; $file";
1778 print_simple_box_start();
1779 echo get_string("lastmodified").": ";
1780 echo userdate($submission->timemodified);
1781 echo $this->display_lateness($submission->timemodified);
1783 $this->print_user_files($user->id);
1785 echo '<br />';
1787 if (empty($submission->timemarked)) {
1788 print_string("notgradedyet", "assignment");
1789 } else {
1790 $this->view_feedback($submission);
1793 print_simple_box_end();
1795 } else {
1796 print_string("notsubmittedyet", "assignment");
1801 * Return a string indicating how late a submission is
1803 * @param $timesubmitted int
1804 * @return string
1806 function display_lateness($timesubmitted) {
1807 return assignment_display_lateness($timesubmitted, $this->assignment->timedue);
1811 * Empty method stub for all delete actions.
1813 function delete() {
1814 //nothing by default
1815 redirect('view.php?id='.$this->cm->id);
1819 * Empty custom feedback grading form.
1821 function custom_feedbackform($submission, $return=false) {
1822 //nothing by default
1823 return '';
1827 * Add a get_coursemodule_info function in case any assignment type wants to add 'extra' information
1828 * for the course (see resource).
1830 * Given a course_module object, this function returns any "extra" information that may be needed
1831 * when printing this activity in a course listing. See get_array_of_activities() in course/lib.php.
1833 * @param $coursemodule object The coursemodule object (record).
1834 * @return object An object on information that the coures will know about (most noticeably, an icon).
1837 function get_coursemodule_info($coursemodule) {
1838 return false;
1842 * Plugin cron method - do not use $this here, create new assignment instances if needed.
1843 * @return void
1845 function cron() {
1846 //no plugin cron by default - override if needed
1850 * Reset all submissions
1852 function reset_userdata($data) {
1853 global $CFG;
1854 require_once($CFG->libdir.'/filelib.php');
1856 if (!count_records('assignment', 'course', $data->courseid, 'assignmenttype', $this->type)) {
1857 return array(); // no assignments of this type present
1860 $componentstr = get_string('modulenameplural', 'assignment');
1861 $status = array();
1863 $typestr = get_string('type'.$this->type, 'assignment');
1865 if (!empty($data->reset_assignment_submissions)) {
1866 $assignmentssql = "SELECT a.id
1867 FROM {$CFG->prefix}assignment a
1868 WHERE a.course={$data->courseid} AND a.assignmenttype='{$this->type}'";
1870 delete_records_select('assignment_submissions', "assignment IN ($assignmentssql)");
1872 if ($assignments = get_records_sql($assignmentssql)) {
1873 foreach ($assignments as $assignmentid=>$unused) {
1874 fulldelete($CFG->dataroot.'/'.$data->courseid.'/moddata/assignment/'.$assignmentid);
1878 $status[] = array('component'=>$componentstr, 'item'=>get_string('deleteallsubmissions','assignment').': '.$typestr, 'error'=>false);
1880 if (empty($data->reset_gradebook_grades)) {
1881 // remove all grades from gradebook
1882 assignment_reset_gradebook($data->courseid, $this->type);
1886 /// updating dates - shift may be negative too
1887 if ($data->timeshift) {
1888 shift_course_mod_dates('assignment', array('timedue', 'timeavailable'), $data->timeshift, $data->courseid);
1889 $status[] = array('component'=>$componentstr, 'item'=>get_string('datechanged').': '.$typestr, 'error'=>false);
1892 return $status;
1894 } ////// End of the assignment_base class
1898 /// OTHER STANDARD FUNCTIONS ////////////////////////////////////////////////////////
1901 * Deletes an assignment instance
1903 * This is done by calling the delete_instance() method of the assignment type class
1905 function assignment_delete_instance($id){
1906 global $CFG;
1908 if (! $assignment = get_record('assignment', 'id', $id)) {
1909 return false;
1912 // fall back to base class if plugin missing
1913 $classfile = "$CFG->dirroot/mod/assignment/type/$assignment->assignmenttype/assignment.class.php";
1914 if (file_exists($classfile)) {
1915 require_once($classfile);
1916 $assignmentclass = "assignment_$assignment->assignmenttype";
1918 } else {
1919 debugging("Missing assignment plug-in: {$assignment->assignmenttype}. Using base class for deleting instead.");
1920 $assignmentclass = "assignment_base";
1923 $ass = new $assignmentclass();
1924 return $ass->delete_instance($assignment);
1929 * Updates an assignment instance
1931 * This is done by calling the update_instance() method of the assignment type class
1933 function assignment_update_instance($assignment){
1934 global $CFG;
1936 $assignment->assignmenttype = clean_param($assignment->assignmenttype, PARAM_SAFEDIR);
1938 require_once("$CFG->dirroot/mod/assignment/type/$assignment->assignmenttype/assignment.class.php");
1939 $assignmentclass = "assignment_$assignment->assignmenttype";
1940 $ass = new $assignmentclass();
1941 return $ass->update_instance($assignment);
1946 * Adds an assignment instance
1948 * This is done by calling the add_instance() method of the assignment type class
1950 function assignment_add_instance($assignment) {
1951 global $CFG;
1953 $assignment->assignmenttype = clean_param($assignment->assignmenttype, PARAM_SAFEDIR);
1955 require_once("$CFG->dirroot/mod/assignment/type/$assignment->assignmenttype/assignment.class.php");
1956 $assignmentclass = "assignment_$assignment->assignmenttype";
1957 $ass = new $assignmentclass();
1958 return $ass->add_instance($assignment);
1963 * Returns an outline of a user interaction with an assignment
1965 * This is done by calling the user_outline() method of the assignment type class
1967 function assignment_user_outline($course, $user, $mod, $assignment) {
1968 global $CFG;
1970 require_once("$CFG->dirroot/mod/assignment/type/$assignment->assignmenttype/assignment.class.php");
1971 $assignmentclass = "assignment_$assignment->assignmenttype";
1972 $ass = new $assignmentclass($mod->id, $assignment, $mod, $course);
1973 return $ass->user_outline($user);
1977 * Prints the complete info about a user's interaction with an assignment
1979 * This is done by calling the user_complete() method of the assignment type class
1981 function assignment_user_complete($course, $user, $mod, $assignment) {
1982 global $CFG;
1984 require_once("$CFG->dirroot/mod/assignment/type/$assignment->assignmenttype/assignment.class.php");
1985 $assignmentclass = "assignment_$assignment->assignmenttype";
1986 $ass = new $assignmentclass($mod->id, $assignment, $mod, $course);
1987 return $ass->user_complete($user);
1991 * Function to be run periodically according to the moodle cron
1993 * Finds all assignment notifications that have yet to be mailed out, and mails them
1995 function assignment_cron () {
1997 global $CFG, $USER;
1999 /// first execute all crons in plugins
2000 if ($plugins = get_list_of_plugins('mod/assignment/type')) {
2001 foreach ($plugins as $plugin) {
2002 require_once("$CFG->dirroot/mod/assignment/type/$plugin/assignment.class.php");
2003 $assignmentclass = "assignment_$plugin";
2004 $ass = new $assignmentclass();
2005 $ass->cron();
2009 /// Notices older than 1 day will not be mailed. This is to avoid the problem where
2010 /// cron has not been running for a long time, and then suddenly people are flooded
2011 /// with mail from the past few weeks or months
2013 $timenow = time();
2014 $endtime = $timenow - $CFG->maxeditingtime;
2015 $starttime = $endtime - 24 * 3600; /// One day earlier
2017 if ($submissions = assignment_get_unmailed_submissions($starttime, $endtime)) {
2019 $CFG->enablerecordcache = true; // We want all the caching we can get
2021 $realuser = clone($USER);
2023 foreach ($submissions as $key => $submission) {
2024 if (! set_field("assignment_submissions", "mailed", "1", "id", "$submission->id")) {
2025 echo "Could not update the mailed field for id $submission->id. Not mailed.\n";
2026 unset($submissions[$key]);
2030 $timenow = time();
2032 foreach ($submissions as $submission) {
2034 echo "Processing assignment submission $submission->id\n";
2036 if (! $user = get_record("user", "id", "$submission->userid")) {
2037 echo "Could not find user $post->userid\n";
2038 continue;
2041 if (! $course = get_record("course", "id", "$submission->course")) {
2042 echo "Could not find course $submission->course\n";
2043 continue;
2046 /// Override the language and timezone of the "current" user, so that
2047 /// mail is customised for the receiver.
2048 $USER = $user;
2049 course_setup($course);
2051 if (!has_capability('moodle/course:view', get_context_instance(CONTEXT_COURSE, $submission->course), $user->id)) {
2052 echo fullname($user)." not an active participant in " . format_string($course->shortname) . "\n";
2053 continue;
2056 if (! $teacher = get_record("user", "id", "$submission->teacher")) {
2057 echo "Could not find teacher $submission->teacher\n";
2058 continue;
2061 if (! $mod = get_coursemodule_from_instance("assignment", $submission->assignment, $course->id)) {
2062 echo "Could not find course module for assignment id $submission->assignment\n";
2063 continue;
2066 if (! $mod->visible) { /// Hold mail notification for hidden assignments until later
2067 continue;
2070 $strassignments = get_string("modulenameplural", "assignment");
2071 $strassignment = get_string("modulename", "assignment");
2073 $assignmentinfo = new object();
2074 $assignmentinfo->teacher = fullname($teacher);
2075 $assignmentinfo->assignment = format_string($submission->name,true);
2076 $assignmentinfo->url = "$CFG->wwwroot/mod/assignment/view.php?id=$mod->id";
2078 $postsubject = "$course->shortname: $strassignments: ".format_string($submission->name,true);
2079 $posttext = "$course->shortname -> $strassignments -> ".format_string($submission->name,true)."\n";
2080 $posttext .= "---------------------------------------------------------------------\n";
2081 $posttext .= get_string("assignmentmail", "assignment", $assignmentinfo)."\n";
2082 $posttext .= "---------------------------------------------------------------------\n";
2084 if ($user->mailformat == 1) { // HTML
2085 $posthtml = "<p><font face=\"sans-serif\">".
2086 "<a href=\"$CFG->wwwroot/course/view.php?id=$course->id\">$course->shortname</a> ->".
2087 "<a href=\"$CFG->wwwroot/mod/assignment/index.php?id=$course->id\">$strassignments</a> ->".
2088 "<a href=\"$CFG->wwwroot/mod/assignment/view.php?id=$mod->id\">".format_string($submission->name,true)."</a></font></p>";
2089 $posthtml .= "<hr /><font face=\"sans-serif\">";
2090 $posthtml .= "<p>".get_string("assignmentmailhtml", "assignment", $assignmentinfo)."</p>";
2091 $posthtml .= "</font><hr />";
2092 } else {
2093 $posthtml = "";
2096 if (! email_to_user($user, $teacher, $postsubject, $posttext, $posthtml)) {
2097 echo "Error: assignment cron: Could not send out mail for id $submission->id to user $user->id ($user->email)\n";
2101 $USER = $realuser;
2102 course_setup(SITEID); // reset cron user language, theme and timezone settings
2106 return true;
2110 * Return grade for given user or all users.
2112 * @param int $assignmentid id of assignment
2113 * @param int $userid optional user id, 0 means all users
2114 * @return array array of grades, false if none
2116 function assignment_get_user_grades($assignment, $userid=0) {
2117 global $CFG;
2119 $user = $userid ? "AND u.id = $userid" : "";
2121 $sql = "SELECT u.id, u.id AS userid, s.grade AS rawgrade, s.submissioncomment AS feedback, s.format AS feedbackformat,
2122 s.teacher AS usermodified, s.timemarked AS dategraded, s.timemodified AS datesubmitted
2123 FROM {$CFG->prefix}user u, {$CFG->prefix}assignment_submissions s
2124 WHERE u.id = s.userid AND s.assignment = $assignment->id
2125 $user";
2127 return get_records_sql($sql);
2131 * Update grades by firing grade_updated event
2133 * @param object $assignment null means all assignments
2134 * @param int $userid specific user only, 0 mean all
2136 function assignment_update_grades($assignment=null, $userid=0, $nullifnone=true) {
2137 global $CFG;
2138 if (!function_exists('grade_update')) { //workaround for buggy PHP versions
2139 require_once($CFG->libdir.'/gradelib.php');
2142 if ($assignment != null) {
2143 if ($grades = assignment_get_user_grades($assignment, $userid)) {
2144 foreach($grades as $k=>$v) {
2145 if ($v->rawgrade == -1) {
2146 $grades[$k]->rawgrade = null;
2149 assignment_grade_item_update($assignment, $grades);
2150 } else {
2151 assignment_grade_item_update($assignment);
2154 } else {
2155 $sql = "SELECT a.*, cm.idnumber as cmidnumber, a.course as courseid
2156 FROM {$CFG->prefix}assignment a, {$CFG->prefix}course_modules cm, {$CFG->prefix}modules m
2157 WHERE m.name='assignment' AND m.id=cm.module AND cm.instance=a.id";
2158 if ($rs = get_recordset_sql($sql)) {
2159 while ($assignment = rs_fetch_next_record($rs)) {
2160 if ($assignment->grade != 0) {
2161 assignment_update_grades($assignment);
2162 } else {
2163 assignment_grade_item_update($assignment);
2166 rs_close($rs);
2172 * Create grade item for given assignment
2174 * @param object $assignment object with extra cmidnumber
2175 * @param mixed optional array/object of grade(s); 'reset' means reset grades in gradebook
2176 * @return int 0 if ok, error code otherwise
2178 function assignment_grade_item_update($assignment, $grades=NULL) {
2179 global $CFG;
2180 if (!function_exists('grade_update')) { //workaround for buggy PHP versions
2181 require_once($CFG->libdir.'/gradelib.php');
2184 if (!isset($assignment->courseid)) {
2185 $assignment->courseid = $assignment->course;
2188 $params = array('itemname'=>$assignment->name, 'idnumber'=>$assignment->cmidnumber);
2190 if ($assignment->grade > 0) {
2191 $params['gradetype'] = GRADE_TYPE_VALUE;
2192 $params['grademax'] = $assignment->grade;
2193 $params['grademin'] = 0;
2195 } else if ($assignment->grade < 0) {
2196 $params['gradetype'] = GRADE_TYPE_SCALE;
2197 $params['scaleid'] = -$assignment->grade;
2199 } else {
2200 $params['gradetype'] = GRADE_TYPE_NONE;
2203 if ($grades === 'reset') {
2204 $params['reset'] = true;
2205 $grades = NULL;
2208 return grade_update('mod/assignment', $assignment->courseid, 'mod', 'assignment', $assignment->id, 0, $grades, $params);
2212 * Delete grade item for given assignment
2214 * @param object $assignment object
2215 * @return object assignment
2217 function assignment_grade_item_delete($assignment) {
2218 global $CFG;
2219 require_once($CFG->libdir.'/gradelib.php');
2221 if (!isset($assignment->courseid)) {
2222 $assignment->courseid = $assignment->course;
2225 return grade_update('mod/assignment', $assignment->courseid, 'mod', 'assignment', $assignment->id, 0, NULL, array('deleted'=>1));
2229 * Returns the users with data in one assignment (students and teachers)
2231 * @param $assignmentid int
2232 * @return array of user objects
2234 function assignment_get_participants($assignmentid) {
2236 global $CFG;
2238 //Get students
2239 $students = get_records_sql("SELECT DISTINCT u.id, u.id
2240 FROM {$CFG->prefix}user u,
2241 {$CFG->prefix}assignment_submissions a
2242 WHERE a.assignment = '$assignmentid' and
2243 u.id = a.userid");
2244 //Get teachers
2245 $teachers = get_records_sql("SELECT DISTINCT u.id, u.id
2246 FROM {$CFG->prefix}user u,
2247 {$CFG->prefix}assignment_submissions a
2248 WHERE a.assignment = '$assignmentid' and
2249 u.id = a.teacher");
2251 //Add teachers to students
2252 if ($teachers) {
2253 foreach ($teachers as $teacher) {
2254 $students[$teacher->id] = $teacher;
2257 //Return students array (it contains an array of unique users)
2258 return ($students);
2262 * Checks if a scale is being used by an assignment
2264 * This is used by the backup code to decide whether to back up a scale
2265 * @param $assignmentid int
2266 * @param $scaleid int
2267 * @return boolean True if the scale is used by the assignment
2269 function assignment_scale_used($assignmentid, $scaleid) {
2271 $return = false;
2273 $rec = get_record('assignment','id',$assignmentid,'grade',-$scaleid);
2275 if (!empty($rec) && !empty($scaleid)) {
2276 $return = true;
2279 return $return;
2283 * Checks if scale is being used by any instance of assignment
2285 * This is used to find out if scale used anywhere
2286 * @param $scaleid int
2287 * @return boolean True if the scale is used by any assignment
2289 function assignment_scale_used_anywhere($scaleid) {
2290 if ($scaleid and record_exists('assignment', 'grade', -$scaleid)) {
2291 return true;
2292 } else {
2293 return false;
2298 * Make sure up-to-date events are created for all assignment instances
2300 * This standard function will check all instances of this module
2301 * and make sure there are up-to-date events created for each of them.
2302 * If courseid = 0, then every assignment event in the site is checked, else
2303 * only assignment events belonging to the course specified are checked.
2304 * This function is used, in its new format, by restore_refresh_events()
2306 * @param $courseid int optional If zero then all assignments for all courses are covered
2307 * @return boolean Always returns true
2309 function assignment_refresh_events($courseid = 0) {
2311 if ($courseid == 0) {
2312 if (! $assignments = get_records("assignment")) {
2313 return true;
2315 } else {
2316 if (! $assignments = get_records("assignment", "course", $courseid)) {
2317 return true;
2320 $moduleid = get_field('modules', 'id', 'name', 'assignment');
2322 foreach ($assignments as $assignment) {
2323 $event = NULL;
2324 $event->name = addslashes($assignment->name);
2325 $event->description = addslashes($assignment->description);
2326 $event->timestart = $assignment->timedue;
2328 if ($event->id = get_field('event', 'id', 'modulename', 'assignment', 'instance', $assignment->id)) {
2329 update_event($event);
2331 } else {
2332 $event->courseid = $assignment->course;
2333 $event->groupid = 0;
2334 $event->userid = 0;
2335 $event->modulename = 'assignment';
2336 $event->instance = $assignment->id;
2337 $event->eventtype = 'due';
2338 $event->timeduration = 0;
2339 $event->visible = get_field('course_modules', 'visible', 'module', $moduleid, 'instance', $assignment->id);
2340 add_event($event);
2344 return true;
2348 * Print recent activity from all assignments in a given course
2350 * This is used by the recent activity block
2352 function assignment_print_recent_activity($course, $viewfullnames, $timestart) {
2353 global $CFG, $USER;
2355 // do not use log table if possible, it may be huge
2357 if (!$submissions = get_records_sql("SELECT asb.id, asb.timemodified, cm.id AS cmid, asb.userid,
2358 u.firstname, u.lastname, u.email, u.picture
2359 FROM {$CFG->prefix}assignment_submissions asb
2360 JOIN {$CFG->prefix}assignment a ON a.id = asb.assignment
2361 JOIN {$CFG->prefix}course_modules cm ON cm.instance = a.id
2362 JOIN {$CFG->prefix}modules md ON md.id = cm.module
2363 JOIN {$CFG->prefix}user u ON u.id = asb.userid
2364 WHERE asb.timemodified > $timestart AND
2365 a.course = {$course->id} AND
2366 md.name = 'assignment'
2367 ORDER BY asb.timemodified ASC")) {
2368 return false;
2371 $modinfo =& get_fast_modinfo($course); // reference needed because we might load the groups
2372 $show = array();
2373 $grader = array();
2375 foreach($submissions as $submission) {
2376 if (!array_key_exists($submission->cmid, $modinfo->cms)) {
2377 continue;
2379 $cm = $modinfo->cms[$submission->cmid];
2380 if (!$cm->uservisible) {
2381 continue;
2383 if ($submission->userid == $USER->id) {
2384 $show[] = $submission;
2385 continue;
2388 // the act of sumitting of assignemnt may be considered private - only graders will see it if specified
2389 if (empty($CFG->assignment_showrecentsubmissions)) {
2390 if (!array_key_exists($cm->id, $grader)) {
2391 $grader[$cm->id] = has_capability('moodle/grade:viewall', get_context_instance(CONTEXT_MODULE, $cm->id));
2393 if (!$grader[$cm->id]) {
2394 continue;
2398 $groupmode = groups_get_activity_groupmode($cm, $course);
2400 if ($groupmode == SEPARATEGROUPS and !has_capability('moodle/site:accessallgroups', get_context_instance(CONTEXT_MODULE, $cm->id))) {
2401 if (isguestuser()) {
2402 // shortcut - guest user does not belong into any group
2403 continue;
2406 if (is_null($modinfo->groups)) {
2407 $modinfo->groups = groups_get_user_groups($course->id); // load all my groups and cache it in modinfo
2410 // this will be slow - show only users that share group with me in this cm
2411 if (empty($modinfo->groups[$cm->id])) {
2412 continue;
2414 $usersgroups = groups_get_all_groups($course->id, $cm->userid, $cm->groupingid);
2415 if (is_array($usersgroups)) {
2416 $usersgroups = array_keys($usersgroups);
2417 $interset = array_intersect($usersgroups, $modinfo->groups[$cm->id]);
2418 if (empty($intersect)) {
2419 continue;
2423 $show[] = $submission;
2426 if (empty($show)) {
2427 return false;
2430 print_headline(get_string('newsubmissions', 'assignment').':');
2432 foreach ($show as $submission) {
2433 $cm = $modinfo->cms[$submission->cmid];
2434 $link = $CFG->wwwroot.'/mod/assignment/view.php?id='.$cm->id;
2435 print_recent_activity_note($submission->timemodified, $submission, $cm->name, $link, false, $viewfullnames);
2438 return true;
2443 * Returns all assignments since a given time in specified forum.
2445 function assignment_get_recent_mod_activity(&$activities, &$index, $timestart, $courseid, $cmid, $userid=0, $groupid=0) {
2447 global $CFG, $COURSE, $USER;
2449 if ($COURSE->id == $courseid) {
2450 $course = $COURSE;
2451 } else {
2452 $course = get_record('course', 'id', $courseid);
2455 $modinfo =& get_fast_modinfo($course);
2457 $cm = $modinfo->cms[$cmid];
2459 if ($userid) {
2460 $userselect = "AND u.id = $userid";
2461 } else {
2462 $userselect = "";
2465 if ($groupid) {
2466 $groupselect = "AND gm.groupid = $groupid";
2467 $groupjoin = "JOIN {$CFG->prefix}groups_members gm ON gm.userid=u.id";
2468 } else {
2469 $groupselect = "";
2470 $groupjoin = "";
2473 if (!$submissions = get_records_sql("SELECT asb.id, asb.timemodified, asb.userid,
2474 u.firstname, u.lastname, u.email, u.picture
2475 FROM {$CFG->prefix}assignment_submissions asb
2476 JOIN {$CFG->prefix}assignment a ON a.id = asb.assignment
2477 JOIN {$CFG->prefix}user u ON u.id = asb.userid
2478 $groupjoin
2479 WHERE asb.timemodified > $timestart AND a.id = $cm->instance
2480 $userselect $groupselect
2481 ORDER BY asb.timemodified ASC")) {
2482 return;
2485 $groupmode = groups_get_activity_groupmode($cm, $course);
2486 $cm_context = get_context_instance(CONTEXT_MODULE, $cm->id);
2487 $grader = has_capability('moodle/grade:viewall', $cm_context);
2488 $accessallgroups = has_capability('moodle/site:accessallgroups', $cm_context);
2489 $viewfullnames = has_capability('moodle/site:viewfullnames', $cm_context);
2491 if (is_null($modinfo->groups)) {
2492 $modinfo->groups = groups_get_user_groups($course->id); // load all my groups and cache it in modinfo
2495 $show = array();
2497 foreach($submissions as $submission) {
2498 if ($submission->userid == $USER->id) {
2499 $show[] = $submission;
2500 continue;
2503 // the act of sumitting of assignemnt may be considered private - only graders will see it if specified
2504 if (!empty($CFG->assignment_limitrecentsubmissions)) {
2505 if (!$grader) {
2506 continue;
2510 if ($groupmode == SEPARATEGROUPS and !$accessallgroups) {
2511 if (isguestuser()) {
2512 // shortcut - guest user does not belong into any group
2513 continue;
2516 // this will be slow - show only users that share group with me in this cm
2517 if (empty($modinfo->groups[$cm->id])) {
2518 continue;
2520 $usersgroups = groups_get_all_groups($course->id, $cm->userid, $cm->groupingid);
2521 if (is_array($usersgroups)) {
2522 $usersgroups = array_keys($usersgroups);
2523 $interset = array_intersect($usersgroups, $modinfo->groups[$cm->id]);
2524 if (empty($intersect)) {
2525 continue;
2529 $show[] = $submission;
2532 if (empty($show)) {
2533 return;
2536 if ($grader) {
2537 require_once($CFG->libdir.'/gradelib.php');
2538 $userids = array();
2539 foreach ($show as $id=>$submission) {
2540 $userids[] = $submission->userid;
2543 $grades = grade_get_grades($courseid, 'mod', 'assignment', $cm->instance, $userids);
2546 $aname = format_string($cm->name,true);
2547 foreach ($show as $submission) {
2548 $tmpactivity = new object();
2550 $tmpactivity->type = 'assignment';
2551 $tmpactivity->cmid = $cm->id;
2552 $tmpactivity->name = $aname;
2553 $tmpactivity->sectionnum = $cm->sectionnum;
2554 $tmpactivity->timestamp = $submission->timemodified;
2556 if ($grader) {
2557 $tmpactivity->grade = $grades->items[0]->grades[$submission->userid]->str_long_grade;
2560 $tmpactivity->user->userid = $submission->userid;
2561 $tmpactivity->user->fullname = fullname($submission, $viewfullnames);
2562 $tmpactivity->user->picture = $submission->picture;
2564 $activities[$index++] = $tmpactivity;
2567 return;
2571 * Print recent activity from all assignments in a given course
2573 * This is used by course/recent.php
2575 function assignment_print_recent_mod_activity($activity, $courseid, $detail, $modnames) {
2576 global $CFG;
2578 echo '<table border="0" cellpadding="3" cellspacing="0" class="assignment-recent">';
2580 echo "<tr><td class=\"userpicture\" valign=\"top\">";
2581 print_user_picture($activity->user->userid, $courseid, $activity->user->picture);
2582 echo "</td><td>";
2584 if ($detail) {
2585 $modname = $modnames[$activity->type];
2586 echo '<div class="title">';
2587 echo "<img src=\"$CFG->modpixpath/assignment/icon.gif\" ".
2588 "class=\"icon\" alt=\"$modname\">";
2589 echo "<a href=\"$CFG->wwwroot/mod/assignment/view.php?id={$activity->cmid}\">{$activity->name}</a>";
2590 echo '</div>';
2593 if (isset($activity->grade)) {
2594 echo '<div class="grade">';
2595 echo get_string('grade').': ';
2596 echo $activity->grade;
2597 echo '</div>';
2600 echo '<div class="user">';
2601 echo "<a href=\"$CFG->wwwroot/user/view.php?id={$activity->user->userid}&amp;course=$courseid\">"
2602 ."{$activity->user->fullname}</a> - ".userdate($activity->timestamp);
2603 echo '</div>';
2605 echo "</td></tr></table>";
2608 /// GENERIC SQL FUNCTIONS
2611 * Fetch info from logs
2613 * @param $log object with properties ->info (the assignment id) and ->userid
2614 * @return array with assignment name and user firstname and lastname
2616 function assignment_log_info($log) {
2617 global $CFG;
2618 return get_record_sql("SELECT a.name, u.firstname, u.lastname
2619 FROM {$CFG->prefix}assignment a,
2620 {$CFG->prefix}user u
2621 WHERE a.id = '$log->info'
2622 AND u.id = '$log->userid'");
2626 * Return list of marked submissions that have not been mailed out for currently enrolled students
2628 * @return array
2630 function assignment_get_unmailed_submissions($starttime, $endtime) {
2632 global $CFG;
2634 return get_records_sql("SELECT s.*, a.course, a.name
2635 FROM {$CFG->prefix}assignment_submissions s,
2636 {$CFG->prefix}assignment a
2637 WHERE s.mailed = 0
2638 AND s.timemarked <= $endtime
2639 AND s.timemarked >= $starttime
2640 AND s.assignment = a.id");
2642 /* return get_records_sql("SELECT s.*, a.course, a.name
2643 FROM {$CFG->prefix}assignment_submissions s,
2644 {$CFG->prefix}assignment a,
2645 {$CFG->prefix}user_students us
2646 WHERE s.mailed = 0
2647 AND s.timemarked <= $endtime
2648 AND s.timemarked >= $starttime
2649 AND s.assignment = a.id
2650 AND s.userid = us.userid
2651 AND a.course = us.course");
2656 * Counts all real assignment submissions by ENROLLED students (not empty ones)
2658 * There are also assignment type methods count_real_submissions() wich in the default
2659 * implementation simply call this function.
2660 * @param $groupid int optional If nonzero then count is restricted to this group
2661 * @return int The number of submissions
2663 function assignment_count_real_submissions($cm, $groupid=0) {
2664 global $CFG;
2666 $context = get_context_instance(CONTEXT_MODULE, $cm->id);
2668 // this is all the users with this capability set, in this context or higher
2669 if ($users = get_users_by_capability($context, 'mod/assignment:submit', 'u.id', '', '', '', $groupid, '', false)) {
2670 $users = array_keys($users);
2673 // if groupmembersonly used, remove users who are not in any group
2674 if ($users and !empty($CFG->enablegroupings) and $cm->groupmembersonly) {
2675 if ($groupingusers = groups_get_grouping_members($cm->groupingid, 'u.id', 'u.id')) {
2676 $users = array_intersect($users, array_keys($groupingusers));
2680 if (empty($users)) {
2681 return 0;
2684 $userlists = implode(',', $users);
2686 return count_records_sql("SELECT COUNT('x')
2687 FROM {$CFG->prefix}assignment_submissions
2688 WHERE assignment = $cm->instance AND
2689 timemodified > 0 AND
2690 userid IN ($userlists)");
2695 * Return all assignment submissions by ENROLLED students (even empty)
2697 * There are also assignment type methods get_submissions() wich in the default
2698 * implementation simply call this function.
2699 * @param $sort string optional field names for the ORDER BY in the sql query
2700 * @param $dir string optional specifying the sort direction, defaults to DESC
2701 * @return array The submission objects indexed by id
2703 function assignment_get_all_submissions($assignment, $sort="", $dir="DESC") {
2704 /// Return all assignment submissions by ENROLLED students (even empty)
2705 global $CFG;
2707 if ($sort == "lastname" or $sort == "firstname") {
2708 $sort = "u.$sort $dir";
2709 } else if (empty($sort)) {
2710 $sort = "a.timemodified DESC";
2711 } else {
2712 $sort = "a.$sort $dir";
2715 /* not sure this is needed at all since assignmenet already has a course define, so this join?
2716 $select = "s.course = '$assignment->course' AND";
2717 if ($assignment->course == SITEID) {
2718 $select = '';
2721 return get_records_sql("SELECT a.*
2722 FROM {$CFG->prefix}assignment_submissions a,
2723 {$CFG->prefix}user u
2724 WHERE u.id = a.userid
2725 AND a.assignment = '$assignment->id'
2726 ORDER BY $sort");
2728 /* return get_records_sql("SELECT a.*
2729 FROM {$CFG->prefix}assignment_submissions a,
2730 {$CFG->prefix}user_students s,
2731 {$CFG->prefix}user u
2732 WHERE a.userid = s.userid
2733 AND u.id = a.userid
2734 AND $select a.assignment = '$assignment->id'
2735 ORDER BY $sort");
2740 * Add a get_coursemodule_info function in case any assignment type wants to add 'extra' information
2741 * for the course (see resource).
2743 * Given a course_module object, this function returns any "extra" information that may be needed
2744 * when printing this activity in a course listing. See get_array_of_activities() in course/lib.php.
2746 * @param $coursemodule object The coursemodule object (record).
2747 * @return object An object on information that the coures will know about (most noticeably, an icon).
2750 function assignment_get_coursemodule_info($coursemodule) {
2751 global $CFG;
2753 if (! $assignment = get_record('assignment', 'id', $coursemodule->instance, '', '', '', '', 'id, assignmenttype, name')) {
2754 return false;
2757 $libfile = "$CFG->dirroot/mod/assignment/type/$assignment->assignmenttype/assignment.class.php";
2759 if (file_exists($libfile)) {
2760 require_once($libfile);
2761 $assignmentclass = "assignment_$assignment->assignmenttype";
2762 $ass = new $assignmentclass('staticonly');
2763 if ($result = $ass->get_coursemodule_info($coursemodule)) {
2764 return $result;
2765 } else {
2766 $info = new object();
2767 $info->name = $assignment->name;
2768 return $info;
2771 } else {
2772 debugging('Incorrect assignment type: '.$assignment->assignmenttype);
2773 return false;
2779 /// OTHER GENERAL FUNCTIONS FOR ASSIGNMENTS ///////////////////////////////////////
2782 * Returns an array of installed assignment types indexed and sorted by name
2784 * @return array The index is the name of the assignment type, the value its full name from the language strings
2786 function assignment_types() {
2787 $types = array();
2788 $names = get_list_of_plugins('mod/assignment/type');
2789 foreach ($names as $name) {
2790 $types[$name] = get_string('type'.$name, 'assignment');
2792 asort($types);
2793 return $types;
2797 * Executes upgrade scripts for assignment types when necessary
2799 function assignment_upgrade_submodules() {
2801 global $CFG;
2803 /// Install/upgrade assignment types (it uses, simply, the standard plugin architecture)
2804 upgrade_plugins('assignment_type', 'mod/assignment/type', "$CFG->wwwroot/$CFG->admin/index.php");
2808 function assignment_print_overview($courses, &$htmlarray) {
2810 global $USER, $CFG;
2812 if (empty($courses) || !is_array($courses) || count($courses) == 0) {
2813 return array();
2816 if (!$assignments = get_all_instances_in_courses('assignment',$courses)) {
2817 return;
2820 // Do assignment_base::isopen() here without loading the whole thing for speed
2821 foreach ($assignments as $key => $assignment) {
2822 $time = time();
2823 if ($assignment->timedue) {
2824 if ($assignment->preventlate) {
2825 $isopen = ($assignment->timeavailable <= $time && $time <= $assignment->timedue);
2826 } else {
2827 $isopen = ($assignment->timeavailable <= $time);
2830 if (empty($isopen) || empty($assignment->timedue)) {
2831 unset($assignments[$key]);
2835 $strduedate = get_string('duedate', 'assignment');
2836 $strduedateno = get_string('duedateno', 'assignment');
2837 $strgraded = get_string('graded', 'assignment');
2838 $strnotgradedyet = get_string('notgradedyet', 'assignment');
2839 $strnotsubmittedyet = get_string('notsubmittedyet', 'assignment');
2840 $strsubmitted = get_string('submitted', 'assignment');
2841 $strassignment = get_string('modulename', 'assignment');
2842 $strreviewed = get_string('reviewed','assignment');
2844 foreach ($assignments as $assignment) {
2845 $str = '<div class="assignment overview"><div class="name">'.$strassignment. ': '.
2846 '<a '.($assignment->visible ? '':' class="dimmed"').
2847 'title="'.$strassignment.'" href="'.$CFG->wwwroot.
2848 '/mod/assignment/view.php?id='.$assignment->coursemodule.'">'.
2849 $assignment->name.'</a></div>';
2850 if ($assignment->timedue) {
2851 $str .= '<div class="info">'.$strduedate.': '.userdate($assignment->timedue).'</div>';
2852 } else {
2853 $str .= '<div class="info">'.$strduedateno.'</div>';
2855 $context = get_context_instance(CONTEXT_MODULE, $assignment->coursemodule);
2856 if (has_capability('mod/assignment:grade', $context)) {
2858 // count how many people can submit
2859 $submissions = 0; // init
2860 if ($students = get_users_by_capability($context, 'mod/assignment:submit', '', '', '', '', 0, '', false)) {
2861 foreach ($students as $student) {
2862 if (record_exists_sql("SELECT id FROM {$CFG->prefix}assignment_submissions
2863 WHERE assignment = $assignment->id AND
2864 userid = $student->id AND
2865 teacher = 0 AND
2866 timemarked = 0")) {
2867 $submissions++;
2872 if ($submissions) {
2873 $str .= get_string('submissionsnotgraded', 'assignment', $submissions);
2875 } else {
2876 $sql = "SELECT *
2877 FROM {$CFG->prefix}assignment_submissions
2878 WHERE userid = '$USER->id'
2879 AND assignment = '{$assignment->id}'";
2880 if ($submission = get_record_sql($sql)) {
2881 if ($submission->teacher == 0 && $submission->timemarked == 0) {
2882 $str .= $strsubmitted . ', ' . $strnotgradedyet;
2883 } else if ($submission->grade <= 0) {
2884 $str .= $strsubmitted . ', ' . $strreviewed;
2885 } else {
2886 $str .= $strsubmitted . ', ' . $strgraded;
2888 } else {
2889 $str .= $strnotsubmittedyet . ' ' . assignment_display_lateness(time(), $assignment->timedue);
2892 $str .= '</div>';
2893 if (empty($htmlarray[$assignment->course]['assignment'])) {
2894 $htmlarray[$assignment->course]['assignment'] = $str;
2895 } else {
2896 $htmlarray[$assignment->course]['assignment'] .= $str;
2901 function assignment_display_lateness($timesubmitted, $timedue) {
2902 if (!$timedue) {
2903 return '';
2905 $time = $timedue - $timesubmitted;
2906 if ($time < 0) {
2907 $timetext = get_string('late', 'assignment', format_time($time));
2908 return ' (<span class="late">'.$timetext.'</span>)';
2909 } else {
2910 $timetext = get_string('early', 'assignment', format_time($time));
2911 return ' (<span class="early">'.$timetext.'</span>)';
2915 function assignment_get_view_actions() {
2916 return array('view');
2919 function assignment_get_post_actions() {
2920 return array('upload');
2923 function assignment_get_types() {
2924 global $CFG;
2925 $types = array();
2927 $type = new object();
2928 $type->modclass = MOD_CLASS_ACTIVITY;
2929 $type->type = "assignment_group_start";
2930 $type->typestr = '--'.get_string('modulenameplural', 'assignment');
2931 $types[] = $type;
2933 $standardassignments = array('upload','online','uploadsingle','offline');
2934 foreach ($standardassignments as $assignmenttype) {
2935 $type = new object();
2936 $type->modclass = MOD_CLASS_ACTIVITY;
2937 $type->type = "assignment&amp;type=$assignmenttype";
2938 $type->typestr = get_string("type$assignmenttype", 'assignment');
2939 $types[] = $type;
2942 /// Drop-in extra assignment types
2943 $assignmenttypes = get_list_of_plugins('mod/assignment/type');
2944 foreach ($assignmenttypes as $assignmenttype) {
2945 if (!empty($CFG->{'assignment_hide_'.$assignmenttype})) { // Not wanted
2946 continue;
2948 if (!in_array($assignmenttype, $standardassignments)) {
2949 $type = new object();
2950 $type->modclass = MOD_CLASS_ACTIVITY;
2951 $type->type = "assignment&amp;type=$assignmenttype";
2952 $type->typestr = get_string("type$assignmenttype", 'assignment');
2953 $types[] = $type;
2957 $type = new object();
2958 $type->modclass = MOD_CLASS_ACTIVITY;
2959 $type->type = "assignment_group_end";
2960 $type->typestr = '--';
2961 $types[] = $type;
2963 return $types;
2967 * Removes all grades from gradebook
2968 * @param int $courseid
2969 * @param string optional type
2971 function assignment_reset_gradebook($courseid, $type='') {
2972 global $CFG;
2974 $type = $type ? "AND a.assignmenttype='$type'" : '';
2976 $sql = "SELECT a.*, cm.idnumber as cmidnumber, a.course as courseid
2977 FROM {$CFG->prefix}assignment a, {$CFG->prefix}course_modules cm, {$CFG->prefix}modules m
2978 WHERE m.name='assignment' AND m.id=cm.module AND cm.instance=a.id AND a.course=$courseid $type";
2980 if ($assignments = get_records_sql($sql)) {
2981 foreach ($assignments as $assignment) {
2982 assignment_grade_item_update($assignment, 'reset');
2988 * This function is used by the reset_course_userdata function in moodlelib.
2989 * This function will remove all posts from the specified assignment
2990 * and clean up any related data.
2991 * @param $data the data submitted from the reset course.
2992 * @return array status array
2994 function assignment_reset_userdata($data) {
2995 global $CFG;
2997 $status = array();
2999 foreach (get_list_of_plugins('mod/assignment/type') as $type) {
3000 require_once("$CFG->dirroot/mod/assignment/type/$type/assignment.class.php");
3001 $assignmentclass = "assignment_$type";
3002 $ass = new $assignmentclass();
3003 $status = array_merge($status, $ass->reset_userdata($data));
3006 return $status;
3010 * Implementation of the function for printing the form elements that control
3011 * whether the course reset functionality affects the assignment.
3012 * @param $mform form passed by reference
3014 function assignment_reset_course_form_definition(&$mform) {
3015 $mform->addElement('header', 'assignmentheader', get_string('modulenameplural', 'assignment'));
3016 $mform->addElement('advcheckbox', 'reset_assignment_submissions', get_string('deleteallsubmissions','assignment'));
3020 * Course reset form defaults.
3022 function assignment_reset_course_form_defaults($course) {
3023 return array('reset_assignment_submissions'=>1);