MDL-22181 fixed 'random' overriding of assignment idnumbers in gradebook - big thanks...
[moodle.git] / mod / assignment / lib.php
blobdf6da617e53f7c46d4a9790c1e7318ba6572b8dc
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->idnumber; // 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, $CFG->wwwroot . '/mod/assignment/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 if (!$teacher = get_record('user', 'id', $graded_by)) {
238 error('Could not find the teacher');
241 /// Print the feedback
242 print_heading(get_string('feedbackfromteacher', 'assignment', $this->course->teacher)); // TODO: fix teacher string
244 echo '<table cellspacing="0" class="feedback">';
246 echo '<tr>';
247 echo '<td class="left picture">';
248 if ($teacher) {
249 print_user_picture($teacher, $this->course->id, $teacher->picture);
251 echo '</td>';
252 echo '<td class="topic">';
253 echo '<div class="from">';
254 if ($teacher) {
255 echo '<div class="fullname">'.fullname($teacher).'</div>';
257 echo '<div class="time">'.userdate($graded_date).'</div>';
258 echo '</div>';
259 echo '</td>';
260 echo '</tr>';
262 echo '<tr>';
263 echo '<td class="left side">&nbsp;</td>';
264 echo '<td class="content">';
265 echo '<div class="grade">';
266 echo get_string("grade").': '.$grade->str_long_grade;
267 echo '</div>';
268 echo '<div class="clearer"></div>';
270 echo '<div class="comment">';
271 echo $grade->str_feedback;
272 echo '</div>';
273 echo '</tr>';
275 echo '</table>';
279 * Returns a link with info about the state of the assignment submissions
281 * This is used by view_header to put this link at the top right of the page.
282 * For teachers it gives the number of submitted assignments with a link
283 * For students it gives the time of their submission.
284 * This will be suitable for most assignment types.
285 * @param bool $allgroup print all groups info if user can access all groups, suitable for index.php
286 * @return string
288 function submittedlink($allgroups=false) {
289 global $USER;
291 $submitted = '';
293 $context = get_context_instance(CONTEXT_MODULE,$this->cm->id);
294 if (has_capability('mod/assignment:grade', $context)) {
295 if ($allgroups and has_capability('moodle/site:accessallgroups', $context)) {
296 $group = 0;
297 } else {
298 $group = groups_get_activity_group($this->cm);
300 if ($count = $this->count_real_submissions($group)) {
301 $submitted = '<a href="submissions.php?id='.$this->cm->id.'">'.
302 get_string('viewsubmissions', 'assignment', $count).'</a>';
303 } else {
304 $submitted = '<a href="submissions.php?id='.$this->cm->id.'">'.
305 get_string('noattempts', 'assignment').'</a>';
307 } else {
308 if (!empty($USER->id)) {
309 if ($submission = $this->get_submission($USER->id)) {
310 if ($submission->timemodified) {
311 if ($submission->timemodified <= $this->assignment->timedue || empty($this->assignment->timedue)) {
312 $submitted = '<span class="early">'.userdate($submission->timemodified).'</span>';
313 } else {
314 $submitted = '<span class="late">'.userdate($submission->timemodified).'</span>';
321 return $submitted;
325 function setup_elements(&$mform) {
330 * Create a new assignment activity
332 * Given an object containing all the necessary data,
333 * (defined by the form in mod.html) this function
334 * will create a new instance and return the id number
335 * of the new instance.
336 * The due data is added to the calendar
337 * This is common to all assignment types.
339 * @param $assignment object The data from the form on mod.html
340 * @return int The id of the assignment
342 function add_instance($assignment) {
343 global $COURSE;
345 $assignment->timemodified = time();
346 $assignment->courseid = $assignment->course;
348 if ($returnid = insert_record("assignment", $assignment)) {
349 $assignment->id = $returnid;
351 if ($assignment->timedue) {
352 $event = new object();
353 $event->name = $assignment->name;
354 $event->description = $assignment->description;
355 $event->courseid = $assignment->course;
356 $event->groupid = 0;
357 $event->userid = 0;
358 $event->modulename = 'assignment';
359 $event->instance = $returnid;
360 $event->eventtype = 'due';
361 $event->timestart = $assignment->timedue;
362 $event->timeduration = 0;
364 add_event($event);
367 $assignment = stripslashes_recursive($assignment);
368 assignment_grade_item_update($assignment);
373 return $returnid;
377 * Deletes an assignment activity
379 * Deletes all database records, files and calendar events for this assignment.
380 * @param $assignment object The assignment to be deleted
381 * @return boolean False indicates error
383 function delete_instance($assignment) {
384 global $CFG;
386 $assignment->courseid = $assignment->course;
388 $result = true;
390 if (! delete_records('assignment_submissions', 'assignment', $assignment->id)) {
391 $result = false;
394 if (! delete_records('assignment', 'id', $assignment->id)) {
395 $result = false;
398 if (! delete_records('event', 'modulename', 'assignment', 'instance', $assignment->id)) {
399 $result = false;
402 // delete file area with all attachments - ignore errors
403 require_once($CFG->libdir.'/filelib.php');
404 fulldelete($CFG->dataroot.'/'.$assignment->course.'/'.$CFG->moddata.'/assignment/'.$assignment->id);
406 assignment_grade_item_delete($assignment);
408 return $result;
412 * Updates a new assignment activity
414 * Given an object containing all the necessary data,
415 * (defined by the form in mod.html) this function
416 * will update the assignment instance and return the id number
417 * The due date is updated in the calendar
418 * This is common to all assignment types.
420 * @param $assignment object The data from the form on mod.html
421 * @return int The assignment id
423 function update_instance($assignment) {
424 global $COURSE;
426 $assignment->timemodified = time();
428 $assignment->id = $assignment->instance;
429 $assignment->courseid = $assignment->course;
431 if (!update_record('assignment', $assignment)) {
432 return false;
435 if ($assignment->timedue) {
436 $event = new object();
438 if ($event->id = get_field('event', 'id', 'modulename', 'assignment', 'instance', $assignment->id)) {
440 $event->name = $assignment->name;
441 $event->description = $assignment->description;
442 $event->timestart = $assignment->timedue;
444 update_event($event);
445 } else {
446 $event = new object();
447 $event->name = $assignment->name;
448 $event->description = $assignment->description;
449 $event->courseid = $assignment->course;
450 $event->groupid = 0;
451 $event->userid = 0;
452 $event->modulename = 'assignment';
453 $event->instance = $assignment->id;
454 $event->eventtype = 'due';
455 $event->timestart = $assignment->timedue;
456 $event->timeduration = 0;
458 add_event($event);
460 } else {
461 delete_records('event', 'modulename', 'assignment', 'instance', $assignment->id);
464 // get existing grade item
465 $assignment = stripslashes_recursive($assignment);
467 assignment_grade_item_update($assignment);
469 return true;
473 * Update grade item for this submission.
475 function update_grade($submission) {
476 assignment_update_grades($this->assignment, $submission->userid);
480 * Top-level function for handling of submissions called by submissions.php
482 * This is for handling the teacher interaction with the grading interface
483 * This should be suitable for most assignment types.
485 * @param $mode string Specifies the kind of teacher interaction taking place
487 function submissions($mode) {
488 ///The main switch is changed to facilitate
489 ///1) Batch fast grading
490 ///2) Skip to the next one on the popup
491 ///3) Save and Skip to the next one on the popup
493 //make user global so we can use the id
494 global $USER;
496 $mailinfo = optional_param('mailinfo', null, PARAM_BOOL);
497 if (is_null($mailinfo)) {
498 $mailinfo = get_user_preferences('assignment_mailinfo', 0);
499 } else {
500 set_user_preference('assignment_mailinfo', $mailinfo);
503 switch ($mode) {
504 case 'grade': // We are in a popup window grading
505 if ($submission = $this->process_feedback()) {
506 //IE needs proper header with encoding
507 print_header(get_string('feedback', 'assignment').':'.format_string($this->assignment->name));
508 print_heading(get_string('changessaved'));
509 print $this->update_main_listing($submission);
511 close_window();
512 break;
514 case 'single': // We are in a popup window displaying submission
515 $this->display_submission();
516 break;
518 case 'all': // Main window, display everything
519 $this->display_submissions();
520 break;
522 case 'fastgrade':
523 ///do the fast grading stuff - this process should work for all 3 subclasses
525 $grading = false;
526 $commenting = false;
527 $col = false;
528 if (isset($_POST['submissioncomment'])) {
529 $col = 'submissioncomment';
530 $commenting = true;
532 if (isset($_POST['menu'])) {
533 $col = 'menu';
534 $grading = true;
536 if (!$col) {
537 //both submissioncomment and grade columns collapsed..
538 $this->display_submissions();
539 break;
542 foreach ($_POST[$col] as $id => $unusedvalue){
544 $id = (int)$id; //clean parameter name
546 $this->process_outcomes($id);
548 if (!$submission = $this->get_submission($id)) {
549 $submission = $this->prepare_new_submission($id);
550 $newsubmission = true;
551 } else {
552 $newsubmission = false;
554 unset($submission->data1); // Don't need to update this.
555 unset($submission->data2); // Don't need to update this.
557 //for fast grade, we need to check if any changes take place
558 $updatedb = false;
560 if ($grading) {
561 $grade = $_POST['menu'][$id];
562 $updatedb = $updatedb || ($submission->grade != $grade);
563 $submission->grade = $grade;
564 } else {
565 if (!$newsubmission) {
566 unset($submission->grade); // Don't need to update this.
569 if ($commenting) {
570 $commentvalue = trim($_POST['submissioncomment'][$id]);
571 $updatedb = $updatedb || ($submission->submissioncomment != stripslashes($commentvalue));
572 $submission->submissioncomment = $commentvalue;
573 } else {
574 unset($submission->submissioncomment); // Don't need to update this.
577 $submission->teacher = $USER->id;
578 if ($updatedb) {
579 $submission->mailed = (int)(!$mailinfo);
582 $submission->timemarked = time();
584 //if it is not an update, we don't change the last modified time etc.
585 //this will also not write into database if no submissioncomment and grade is entered.
587 if ($updatedb){
588 if ($newsubmission) {
589 if (!isset($submission->submissioncomment)) {
590 $submission->submissioncomment = '';
592 if (!$sid = insert_record('assignment_submissions', $submission)) {
593 return false;
595 $submission->id = $sid;
596 } else {
597 if (!update_record('assignment_submissions', $submission)) {
598 return false;
602 // triger grade event
603 $this->update_grade($submission);
605 //add to log only if updating
606 add_to_log($this->course->id, 'assignment', 'update grades',
607 'submissions.php?id='.$this->assignment->id.'&user='.$submission->userid,
608 $submission->userid, $this->cm->id);
613 $message = notify(get_string('changessaved'), 'notifysuccess', 'center', true);
615 $this->display_submissions($message);
616 break;
619 case 'next':
620 /// We are currently in pop up, but we want to skip to next one without saving.
621 /// This turns out to be similar to a single case
622 /// The URL used is for the next submission.
624 $this->display_submission();
625 break;
627 case 'saveandnext':
628 ///We are in pop up. save the current one and go to the next one.
629 //first we save the current changes
630 if ($submission = $this->process_feedback()) {
631 //print_heading(get_string('changessaved'));
632 $extra_javascript = $this->update_main_listing($submission);
635 //then we display the next submission
636 $this->display_submission($extra_javascript);
637 break;
639 default:
640 echo "something seriously is wrong!!";
641 break;
646 * Helper method updating the listing on the main script from popup using javascript
648 * @param $submission object The submission whose data is to be updated on the main page
650 function update_main_listing($submission) {
651 global $SESSION, $CFG;
653 $output = '';
655 $perpage = get_user_preferences('assignment_perpage', 10);
657 $quickgrade = get_user_preferences('assignment_quickgrade', 0);
659 /// Run some Javascript to try and update the parent page
660 $output .= '<script type="text/javascript">'."\n<!--\n";
661 if (empty($SESSION->flextable['mod-assignment-submissions']->collapse['submissioncomment'])) {
662 if ($quickgrade){
663 $output.= 'opener.document.getElementById("submissioncomment'.$submission->userid.'").value="'
664 .trim($submission->submissioncomment).'";'."\n";
665 } else {
666 $output.= 'opener.document.getElementById("com'.$submission->userid.
667 '").innerHTML="'.shorten_text(trim(strip_tags($submission->submissioncomment)), 15)."\";\n";
671 if (empty($SESSION->flextable['mod-assignment-submissions']->collapse['grade'])) {
672 //echo optional_param('menuindex');
673 if ($quickgrade){
674 $output.= 'opener.document.getElementById("menumenu'.$submission->userid.
675 '").selectedIndex="'.optional_param('menuindex', 0, PARAM_INT).'";'."\n";
676 } else {
677 $output.= 'opener.document.getElementById("g'.$submission->userid.'").innerHTML="'.
678 $this->display_grade($submission->grade)."\";\n";
681 //need to add student's assignments in there too.
682 if (empty($SESSION->flextable['mod-assignment-submissions']->collapse['timemodified']) &&
683 $submission->timemodified) {
684 $output.= 'opener.document.getElementById("ts'.$submission->userid.
685 '").innerHTML="'.addslashes_js($this->print_student_answer($submission->userid)).userdate($submission->timemodified)."\";\n";
688 if (empty($SESSION->flextable['mod-assignment-submissions']->collapse['timemarked']) &&
689 $submission->timemarked) {
690 $output.= 'opener.document.getElementById("tt'.$submission->userid.
691 '").innerHTML="'.userdate($submission->timemarked)."\";\n";
694 if (empty($SESSION->flextable['mod-assignment-submissions']->collapse['status'])) {
695 $output.= 'opener.document.getElementById("up'.$submission->userid.'").className="s1";';
696 $buttontext = get_string('update');
697 $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),
698 'grade'.$submission->userid, $buttontext, 450, 700, $buttontext, 'none', true, 'button'.$submission->userid);
699 $output.= 'opener.document.getElementById("up'.$submission->userid.'").innerHTML="'.addslashes_js($button).'";';
702 $grading_info = grade_get_grades($this->course->id, 'mod', 'assignment', $this->assignment->id, $submission->userid);
704 if (empty($SESSION->flextable['mod-assignment-submissions']->collapse['finalgrade'])) {
705 $output.= 'opener.document.getElementById("finalgrade_'.$submission->userid.
706 '").innerHTML="'.$grading_info->items[0]->grades[$submission->userid]->str_grade.'";'."\n";
709 if (!empty($CFG->enableoutcomes) and empty($SESSION->flextable['mod-assignment-submissions']->collapse['outcome'])) {
711 if (!empty($grading_info->outcomes)) {
712 foreach($grading_info->outcomes as $n=>$outcome) {
713 if ($outcome->grades[$submission->userid]->locked) {
714 continue;
717 if ($quickgrade){
718 $output.= 'opener.document.getElementById("outcome_'.$n.'_'.$submission->userid.
719 '").selectedIndex="'.$outcome->grades[$submission->userid]->grade.'";'."\n";
721 } else {
722 $options = make_grades_menu(-$outcome->scaleid);
723 $options[0] = get_string('nooutcome', 'grades');
724 $output.= 'opener.document.getElementById("outcome_'.$n.'_'.$submission->userid.'").innerHTML="'.$options[$outcome->grades[$submission->userid]->grade]."\";\n";
731 $output .= "\n-->\n</script>";
732 return $output;
736 * Return a grade in user-friendly form, whether it's a scale or not
738 * @param $grade
739 * @return string User-friendly representation of grade
741 function display_grade($grade) {
743 static $scalegrades = array(); // Cache scales for each assignment - they might have different scales!!
745 if ($this->assignment->grade >= 0) { // Normal number
746 if ($grade == -1) {
747 return '-';
748 } else {
749 return $grade.' / '.$this->assignment->grade;
752 } else { // Scale
753 if (empty($scalegrades[$this->assignment->id])) {
754 if ($scale = get_record('scale', 'id', -($this->assignment->grade))) {
755 $scalegrades[$this->assignment->id] = make_menu_from_list($scale->scale);
756 } else {
757 return '-';
760 if (isset($scalegrades[$this->assignment->id][$grade])) {
761 return $scalegrades[$this->assignment->id][$grade];
763 return '-';
768 * Display a single submission, ready for grading on a popup window
770 * This default method prints the teacher info and submissioncomment box at the top and
771 * the student info and submission at the bottom.
772 * This method also fetches the necessary data in order to be able to
773 * provide a "Next submission" button.
774 * Calls preprocess_submission() to give assignment type plug-ins a chance
775 * to process submissions before they are graded
776 * This method gets its arguments from the page parameters userid and offset
778 function display_submission($extra_javascript = '') {
780 global $CFG;
781 require_once($CFG->libdir.'/gradelib.php');
782 require_once($CFG->libdir.'/tablelib.php');
784 $userid = required_param('userid', PARAM_INT);
785 $offset = required_param('offset', PARAM_INT);//offset for where to start looking for student.
787 if (!$user = get_record('user', 'id', $userid)) {
788 error('No such user!');
791 if (!$submission = $this->get_submission($user->id)) {
792 $submission = $this->prepare_new_submission($userid);
794 if ($submission->timemodified > $submission->timemarked) {
795 $subtype = 'assignmentnew';
796 } else {
797 $subtype = 'assignmentold';
800 $grading_info = grade_get_grades($this->course->id, 'mod', 'assignment', $this->assignment->id, array($user->id));
801 $disabled = $grading_info->items[0]->grades[$userid]->locked || $grading_info->items[0]->grades[$userid]->overridden;
803 /// construct SQL, using current offset to find the data of the next student
804 $course = $this->course;
805 $assignment = $this->assignment;
806 $cm = $this->cm;
807 $context = get_context_instance(CONTEXT_MODULE, $cm->id);
809 /// Get all ppl that can submit assignments
811 $currentgroup = groups_get_activity_group($cm);
812 if ($users = get_users_by_capability($context, 'mod/assignment:submit', 'u.id', '', '', '', $currentgroup, '', false)) {
813 $users = array_keys($users);
816 // if groupmembersonly used, remove users who are not in any group
817 if ($users and !empty($CFG->enablegroupings) and $cm->groupmembersonly) {
818 if ($groupingusers = groups_get_grouping_members($cm->groupingid, 'u.id', 'u.id')) {
819 $users = array_intersect($users, array_keys($groupingusers));
823 $nextid = 0;
825 if ($users) {
826 $select = 'SELECT u.id, u.firstname, u.lastname, u.picture, u.imagealt,
827 s.id AS submissionid, s.grade, s.submissioncomment,
828 s.timemodified, s.timemarked,
829 COALESCE(SIGN(SIGN(s.timemarked) + SIGN(s.timemarked - s.timemodified)), 0) AS status ';
830 $sql = 'FROM '.$CFG->prefix.'user u '.
831 'LEFT JOIN '.$CFG->prefix.'assignment_submissions s ON u.id = s.userid
832 AND s.assignment = '.$this->assignment->id.' '.
833 'WHERE u.id IN ('.implode(',', $users).') ';
835 if ($sort = flexible_table::get_sql_sort('mod-assignment-submissions')) {
836 $sort = 'ORDER BY '.$sort.' ';
839 if (($auser = get_records_sql($select.$sql.$sort, $offset+1, 1)) !== false) {
840 $nextuser = array_shift($auser);
841 /// Calculate user status
842 $nextuser->status = ($nextuser->timemarked > 0) && ($nextuser->timemarked >= $nextuser->timemodified);
843 $nextid = $nextuser->id;
847 print_header(get_string('feedback', 'assignment').':'.fullname($user, true).':'.format_string($this->assignment->name));
849 /// Print any extra javascript needed for saveandnext
850 echo $extra_javascript;
852 ///SOme javascript to help with setting up >.>
854 echo '<script type="text/javascript">'."\n";
855 echo 'function setNext(){'."\n";
856 echo 'document.getElementById(\'submitform\').mode.value=\'next\';'."\n";
857 echo 'document.getElementById(\'submitform\').userid.value="'.$nextid.'";'."\n";
858 echo '}'."\n";
860 echo 'function saveNext(){'."\n";
861 echo 'document.getElementById(\'submitform\').mode.value=\'saveandnext\';'."\n";
862 echo 'document.getElementById(\'submitform\').userid.value="'.$nextid.'";'."\n";
863 echo 'document.getElementById(\'submitform\').saveuserid.value="'.$userid.'";'."\n";
864 echo 'document.getElementById(\'submitform\').menuindex.value = document.getElementById(\'submitform\').grade.selectedIndex;'."\n";
865 echo '}'."\n";
867 echo '</script>'."\n";
868 echo '<table cellspacing="0" class="feedback '.$subtype.'" >';
870 ///Start of teacher info row
872 echo '<tr>';
873 echo '<td class="picture teacher">';
874 if ($submission->teacher) {
875 $teacher = get_record('user', 'id', $submission->teacher);
876 } else {
877 global $USER;
878 $teacher = $USER;
880 print_user_picture($teacher, $this->course->id, $teacher->picture);
881 echo '</td>';
882 echo '<td class="content">';
883 echo '<form id="submitform" action="submissions.php" method="post">';
884 echo '<div>'; // xhtml compatibility - invisiblefieldset was breaking layout here
885 echo '<input type="hidden" name="offset" value="'.($offset+1).'" />';
886 echo '<input type="hidden" name="userid" value="'.$userid.'" />';
887 echo '<input type="hidden" name="id" value="'.$this->cm->id.'" />';
888 echo '<input type="hidden" name="sesskey" value="'.sesskey().'" />';
889 echo '<input type="hidden" name="mode" value="grade" />';
890 echo '<input type="hidden" name="menuindex" value="0" />';//selected menu index
892 //new hidden field, initialized to -1.
893 echo '<input type="hidden" name="saveuserid" value="-1" />';
895 if ($submission->timemarked) {
896 echo '<div class="from">';
897 echo '<div class="fullname">'.fullname($teacher, true).'</div>';
898 echo '<div class="time">'.userdate($submission->timemarked).'</div>';
899 echo '</div>';
901 echo '<div class="grade"><label for="menugrade">'.get_string('grade').'</label> ';
902 choose_from_menu(make_grades_menu($this->assignment->grade), 'grade', $submission->grade, get_string('nograde'), '', -1, false, $disabled);
903 echo '</div>';
905 echo '<div class="clearer"></div>';
906 echo '<div class="finalgrade">'.get_string('finalgrade', 'grades').': '.$grading_info->items[0]->grades[$userid]->str_grade.'</div>';
907 echo '<div class="clearer"></div>';
909 if (!empty($CFG->enableoutcomes)) {
910 foreach($grading_info->outcomes as $n=>$outcome) {
911 echo '<div class="outcome"><label for="menuoutcome_'.$n.'">'.$outcome->name.'</label> ';
912 $options = make_grades_menu(-$outcome->scaleid);
913 if ($outcome->grades[$submission->userid]->locked) {
914 $options[0] = get_string('nooutcome', 'grades');
915 echo $options[$outcome->grades[$submission->userid]->grade];
916 } else {
917 choose_from_menu($options, 'outcome_'.$n.'['.$userid.']', $outcome->grades[$submission->userid]->grade, get_string('nooutcome', 'grades'), '', 0, false, false, 0, 'menuoutcome_'.$n);
919 echo '</div>';
920 echo '<div class="clearer"></div>';
925 $this->preprocess_submission($submission);
927 if ($disabled) {
928 echo '<div class="disabledfeedback">'.$grading_info->items[0]->grades[$userid]->str_feedback.'</div>';
930 } else {
931 print_textarea($this->usehtmleditor, 14, 58, 0, 0, 'submissioncomment', $submission->submissioncomment, $this->course->id);
932 if ($this->usehtmleditor) {
933 echo '<input type="hidden" name="format" value="'.FORMAT_HTML.'" />';
934 } else {
935 echo '<div class="format">';
936 choose_from_menu(format_text_menu(), "format", $submission->format, "");
937 helpbutton("textformat", get_string("helpformatting"));
938 echo '</div>';
942 $lastmailinfo = get_user_preferences('assignment_mailinfo', 1) ? 'checked="checked"' : '';
944 ///Print Buttons in Single View
945 echo '<input type="hidden" name="mailinfo" value="0" />';
946 echo '<input type="checkbox" id="mailinfo" name="mailinfo" value="1" '.$lastmailinfo.' /><label for="mailinfo">'.get_string('enableemailnotification','assignment').'</label>';
947 echo '<div class="buttons">';
948 echo '<input type="submit" name="submit" value="'.get_string('savechanges').'" onclick = "document.getElementById(\'submitform\').menuindex.value = document.getElementById(\'submitform\').grade.selectedIndex" />';
949 echo '<input type="submit" name="cancel" value="'.get_string('cancel').'" />';
950 //if there are more to be graded.
951 if ($nextid) {
952 echo '<input type="submit" name="saveandnext" value="'.get_string('saveandnext').'" onclick="saveNext()" />';
953 echo '<input type="submit" name="next" value="'.get_string('next').'" onclick="setNext();" />';
955 echo '</div>';
956 echo '</div></form>';
958 $customfeedback = $this->custom_feedbackform($submission, true);
959 if (!empty($customfeedback)) {
960 echo $customfeedback;
963 echo '</td></tr>';
965 ///End of teacher info row, Start of student info row
966 echo '<tr>';
967 echo '<td class="picture user">';
968 print_user_picture($user, $this->course->id, $user->picture);
969 echo '</td>';
970 echo '<td class="topic">';
971 echo '<div class="from">';
972 echo '<div class="fullname">'.fullname($user, true).'</div>';
973 if ($submission->timemodified) {
974 echo '<div class="time">'.userdate($submission->timemodified).
975 $this->display_lateness($submission->timemodified).'</div>';
977 echo '</div>';
978 $this->print_user_files($user->id);
979 echo '</td>';
980 echo '</tr>';
982 ///End of student info row
984 echo '</table>';
986 if (!$disabled and $this->usehtmleditor) {
987 use_html_editor();
990 print_footer('none');
994 * Preprocess submission before grading
996 * Called by display_submission()
997 * The default type does nothing here.
998 * @param $submission object The submission object
1000 function preprocess_submission(&$submission) {
1004 * Display all the submissions ready for grading
1006 function display_submissions($message='') {
1007 global $CFG, $db, $USER;
1008 require_once($CFG->libdir.'/gradelib.php');
1010 /* first we check to see if the form has just been submitted
1011 * to request user_preference updates
1014 if (isset($_POST['updatepref'])){
1015 $perpage = optional_param('perpage', 10, PARAM_INT);
1016 $perpage = ($perpage <= 0) ? 10 : $perpage ;
1017 set_user_preference('assignment_perpage', $perpage);
1018 set_user_preference('assignment_quickgrade', optional_param('quickgrade', 0, PARAM_BOOL));
1021 /* next we get perpage and quickgrade (allow quick grade) params
1022 * from database
1024 $perpage = get_user_preferences('assignment_perpage', 10);
1026 $quickgrade = get_user_preferences('assignment_quickgrade', 0);
1028 $grading_info = grade_get_grades($this->course->id, 'mod', 'assignment', $this->assignment->id);
1030 if (!empty($CFG->enableoutcomes) and !empty($grading_info->outcomes)) {
1031 $uses_outcomes = true;
1032 } else {
1033 $uses_outcomes = false;
1036 $page = optional_param('page', 0, PARAM_INT);
1037 $strsaveallfeedback = get_string('saveallfeedback', 'assignment');
1039 /// Some shortcuts to make the code read better
1041 $course = $this->course;
1042 $assignment = $this->assignment;
1043 $cm = $this->cm;
1045 $tabindex = 1; //tabindex for quick grading tabbing; Not working for dropdowns yet
1046 add_to_log($course->id, 'assignment', 'view submission', 'submissions.php?id='.$this->cm->id, $this->assignment->id, $this->cm->id);
1047 $navigation = build_navigation($this->strsubmissions, $this->cm);
1048 print_header_simple(format_string($this->assignment->name,true), "", $navigation,
1049 '', '', true, update_module_button($cm->id, $course->id, $this->strassignment), navmenu($course, $cm));
1051 $course_context = get_context_instance(CONTEXT_COURSE, $course->id);
1052 if (has_capability('gradereport/grader:view', $course_context) && has_capability('moodle/grade:viewall', $course_context)) {
1053 echo '<div class="allcoursegrades"><a href="' . $CFG->wwwroot . '/grade/report/grader/index.php?id=' . $course->id . '">'
1054 . get_string('seeallcoursegrades', 'grades') . '</a></div>';
1057 if (!empty($message)) {
1058 echo $message; // display messages here if any
1061 $context = get_context_instance(CONTEXT_MODULE, $cm->id);
1063 /// Check to see if groups are being used in this assignment
1065 /// find out current groups mode
1066 $groupmode = groups_get_activity_groupmode($cm);
1067 $currentgroup = groups_get_activity_group($cm, true);
1068 groups_print_activity_menu($cm, $CFG->wwwroot . '/mod/assignment/submissions.php?id=' . $this->cm->id);
1070 /// Get all ppl that are allowed to submit assignments
1071 if ($users = get_users_by_capability($context, 'mod/assignment:submit', 'u.id', '', '', '', $currentgroup, '', false)) {
1072 $users = array_keys($users);
1075 // if groupmembersonly used, remove users who are not in any group
1076 if ($users and !empty($CFG->enablegroupings) and $cm->groupmembersonly) {
1077 if ($groupingusers = groups_get_grouping_members($cm->groupingid, 'u.id', 'u.id')) {
1078 $users = array_intersect($users, array_keys($groupingusers));
1082 $tablecolumns = array('picture', 'fullname', 'grade', 'submissioncomment', 'timemodified', 'timemarked', 'status', 'finalgrade');
1083 if ($uses_outcomes) {
1084 $tablecolumns[] = 'outcome'; // no sorting based on outcomes column
1087 $tableheaders = array('',
1088 get_string('fullname'),
1089 get_string('grade'),
1090 get_string('comment', 'assignment'),
1091 get_string('lastmodified').' ('.$course->student.')',
1092 get_string('lastmodified').' ('.$course->teacher.')',
1093 get_string('status'),
1094 get_string('finalgrade', 'grades'));
1095 if ($uses_outcomes) {
1096 $tableheaders[] = get_string('outcome', 'grades');
1099 require_once($CFG->libdir.'/tablelib.php');
1100 $table = new flexible_table('mod-assignment-submissions');
1102 $table->define_columns($tablecolumns);
1103 $table->define_headers($tableheaders);
1104 $table->define_baseurl($CFG->wwwroot.'/mod/assignment/submissions.php?id='.$this->cm->id.'&amp;currentgroup='.$currentgroup);
1106 $table->sortable(true, 'lastname');//sorted by lastname by default
1107 $table->collapsible(true);
1108 $table->initialbars(true);
1110 $table->column_suppress('picture');
1111 $table->column_suppress('fullname');
1113 $table->column_class('picture', 'picture');
1114 $table->column_class('fullname', 'fullname');
1115 $table->column_class('grade', 'grade');
1116 $table->column_class('submissioncomment', 'comment');
1117 $table->column_class('timemodified', 'timemodified');
1118 $table->column_class('timemarked', 'timemarked');
1119 $table->column_class('status', 'status');
1120 $table->column_class('finalgrade', 'finalgrade');
1121 if ($uses_outcomes) {
1122 $table->column_class('outcome', 'outcome');
1125 $table->set_attribute('cellspacing', '0');
1126 $table->set_attribute('id', 'attempts');
1127 $table->set_attribute('class', 'submissions');
1128 $table->set_attribute('width', '100%');
1129 //$table->set_attribute('align', 'center');
1131 $table->no_sorting('finalgrade');
1132 $table->no_sorting('outcome');
1134 // Start working -- this is necessary as soon as the niceties are over
1135 $table->setup();
1137 if (empty($users)) {
1138 print_heading(get_string('nosubmitusers','assignment'));
1139 return true;
1142 /// Construct the SQL
1144 if ($where = $table->get_sql_where()) {
1145 $where .= ' AND ';
1148 if ($sort = $table->get_sql_sort()) {
1149 $sort = ' ORDER BY '.$sort;
1152 $select = 'SELECT u.id, u.firstname, u.lastname, u.picture, u.imagealt,
1153 s.id AS submissionid, s.grade, s.submissioncomment,
1154 s.timemodified, s.timemarked,
1155 COALESCE(SIGN(SIGN(s.timemarked) + SIGN(s.timemarked - s.timemodified)), 0) AS status ';
1156 $sql = 'FROM '.$CFG->prefix.'user u '.
1157 'LEFT JOIN '.$CFG->prefix.'assignment_submissions s ON u.id = s.userid
1158 AND s.assignment = '.$this->assignment->id.' '.
1159 'WHERE '.$where.'u.id IN ('.implode(',',$users).') ';
1161 $table->pagesize($perpage, count($users));
1163 ///offset used to calculate index of student in that particular query, needed for the pop up to know who's next
1164 $offset = $page * $perpage;
1166 $strupdate = get_string('update');
1167 $strgrade = get_string('grade');
1168 $grademenu = make_grades_menu($this->assignment->grade);
1170 if (($ausers = get_records_sql($select.$sql.$sort, $table->get_page_start(), $table->get_page_size())) !== false) {
1171 $grading_info = grade_get_grades($this->course->id, 'mod', 'assignment', $this->assignment->id, array_keys($ausers));
1172 foreach ($ausers as $auser) {
1173 $final_grade = $grading_info->items[0]->grades[$auser->id];
1174 $grademax = $grading_info->items[0]->grademax;
1175 $final_grade->formatted_grade = round($final_grade->grade,2) .' / ' . round($grademax,2);
1176 $locked_overridden = 'locked';
1177 if ($final_grade->overridden) {
1178 $locked_overridden = 'overridden';
1181 /// Calculate user status
1182 $auser->status = ($auser->timemarked > 0) && ($auser->timemarked >= $auser->timemodified);
1183 $picture = print_user_picture($auser, $course->id, $auser->picture, false, true);
1185 if (empty($auser->submissionid)) {
1186 $auser->grade = -1; //no submission yet
1189 if (!empty($auser->submissionid)) {
1190 ///Prints student answer and student modified date
1191 ///attach file or print link to student answer, depending on the type of the assignment.
1192 ///Refer to print_student_answer in inherited classes.
1193 if ($auser->timemodified > 0) {
1194 $studentmodified = '<div id="ts'.$auser->id.'">'.$this->print_student_answer($auser->id)
1195 . userdate($auser->timemodified).'</div>';
1196 } else {
1197 $studentmodified = '<div id="ts'.$auser->id.'">&nbsp;</div>';
1199 ///Print grade, dropdown or text
1200 if ($auser->timemarked > 0) {
1201 $teachermodified = '<div id="tt'.$auser->id.'">'.userdate($auser->timemarked).'</div>';
1203 if ($final_grade->locked or $final_grade->overridden) {
1204 $grade = '<div id="g'.$auser->id.'" class="'. $locked_overridden .'">'.$final_grade->formatted_grade.'</div>';
1205 } else if ($quickgrade) {
1206 $menu = choose_from_menu(make_grades_menu($this->assignment->grade),
1207 'menu['.$auser->id.']', $auser->grade,
1208 get_string('nograde'),'',-1,true,false,$tabindex++);
1209 $grade = '<div id="g'.$auser->id.'">'. $menu .'</div>';
1210 } else {
1211 $grade = '<div id="g'.$auser->id.'">'.$this->display_grade($auser->grade).'</div>';
1214 } else {
1215 $teachermodified = '<div id="tt'.$auser->id.'">&nbsp;</div>';
1216 if ($final_grade->locked or $final_grade->overridden) {
1217 $grade = '<div id="g'.$auser->id.'" class="'. $locked_overridden .'">'.$final_grade->formatted_grade.'</div>';
1218 } else if ($quickgrade) {
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.'">'.$this->display_grade($auser->grade).'</div>';
1227 ///Print Comment
1228 if ($final_grade->locked or $final_grade->overridden) {
1229 $comment = '<div id="com'.$auser->id.'">'.shorten_text(strip_tags($final_grade->str_feedback),15).'</div>';
1231 } else if ($quickgrade) {
1232 $comment = '<div id="com'.$auser->id.'">'
1233 . '<textarea tabindex="'.$tabindex++.'" name="submissioncomment['.$auser->id.']" id="submissioncomment'
1234 . $auser->id.'" rows="2" cols="20">'.($auser->submissioncomment).'</textarea></div>';
1235 } else {
1236 $comment = '<div id="com'.$auser->id.'">'.shorten_text(strip_tags($auser->submissioncomment),15).'</div>';
1238 } else {
1239 $studentmodified = '<div id="ts'.$auser->id.'">&nbsp;</div>';
1240 $teachermodified = '<div id="tt'.$auser->id.'">&nbsp;</div>';
1241 $status = '<div id="st'.$auser->id.'">&nbsp;</div>';
1243 if ($final_grade->locked or $final_grade->overridden) {
1244 $grade = '<div id="g'.$auser->id.'">'.$final_grade->formatted_grade . '</div>';
1245 } else if ($quickgrade) { // allow editing
1246 $menu = choose_from_menu(make_grades_menu($this->assignment->grade),
1247 'menu['.$auser->id.']', $auser->grade,
1248 get_string('nograde'),'',-1,true,false,$tabindex++);
1249 $grade = '<div id="g'.$auser->id.'">'.$menu.'</div>';
1250 } else {
1251 $grade = '<div id="g'.$auser->id.'">-</div>';
1254 if ($final_grade->locked or $final_grade->overridden) {
1255 $comment = '<div id="com'.$auser->id.'">'.$final_grade->str_feedback.'</div>';
1256 } else if ($quickgrade) {
1257 $comment = '<div id="com'.$auser->id.'">'
1258 . '<textarea tabindex="'.$tabindex++.'" name="submissioncomment['.$auser->id.']" id="submissioncomment'
1259 . $auser->id.'" rows="2" cols="20">'.($auser->submissioncomment).'</textarea></div>';
1260 } else {
1261 $comment = '<div id="com'.$auser->id.'">&nbsp;</div>';
1265 if (empty($auser->status)) { /// Confirm we have exclusively 0 or 1
1266 $auser->status = 0;
1267 } else {
1268 $auser->status = 1;
1271 $buttontext = ($auser->status == 1) ? $strupdate : $strgrade;
1273 ///No more buttons, we use popups ;-).
1274 $popup_url = '/mod/assignment/submissions.php?id='.$this->cm->id
1275 . '&amp;userid='.$auser->id.'&amp;mode=single'.'&amp;offset='.$offset++;
1276 $button = link_to_popup_window ($popup_url, 'grade'.$auser->id, $buttontext, 600, 780,
1277 $buttontext, 'none', true, 'button'.$auser->id);
1279 $status = '<div id="up'.$auser->id.'" class="s'.$auser->status.'">'.$button.'</div>';
1281 $finalgrade = '<span id="finalgrade_'.$auser->id.'">'.$final_grade->str_grade.'</span>';
1283 $outcomes = '';
1285 if ($uses_outcomes) {
1287 foreach($grading_info->outcomes as $n=>$outcome) {
1288 $outcomes .= '<div class="outcome"><label>'.$outcome->name.'</label>';
1289 $options = make_grades_menu(-$outcome->scaleid);
1291 if ($outcome->grades[$auser->id]->locked or !$quickgrade) {
1292 $options[0] = get_string('nooutcome', 'grades');
1293 $outcomes .= ': <span id="outcome_'.$n.'_'.$auser->id.'">'.$options[$outcome->grades[$auser->id]->grade].'</span>';
1294 } else {
1295 $outcomes .= ' ';
1296 $outcomes .= choose_from_menu($options, 'outcome_'.$n.'['.$auser->id.']',
1297 $outcome->grades[$auser->id]->grade, get_string('nooutcome', 'grades'), '', 0, true, false, 0, 'outcome_'.$n.'_'.$auser->id);
1299 $outcomes .= '</div>';
1303 $userlink = '<a href="' . $CFG->wwwroot . '/user/view.php?id=' . $auser->id . '&amp;course=' . $course->id . '">' . fullname($auser, has_capability('moodle/site:viewfullnames', $this->context)) . '</a>';
1304 $row = array($picture, $userlink, $grade, $comment, $studentmodified, $teachermodified, $status, $finalgrade);
1305 if ($uses_outcomes) {
1306 $row[] = $outcomes;
1309 $table->add_data($row);
1313 /// Print quickgrade form around the table
1314 if ($quickgrade){
1315 echo '<form action="submissions.php" id="fastg" method="post">';
1316 echo '<div>';
1317 echo '<input type="hidden" name="id" value="'.$this->cm->id.'" />';
1318 echo '<input type="hidden" name="mode" value="fastgrade" />';
1319 echo '<input type="hidden" name="page" value="'.$page.'" />';
1320 echo '<input type="hidden" name="sesskey" value="'.sesskey().'" />';
1321 echo '</div>';
1324 $table->print_html(); /// Print the whole table
1326 if ($quickgrade){
1327 $lastmailinfo = get_user_preferences('assignment_mailinfo', 1) ? 'checked="checked"' : '';
1328 echo '<div class="fgcontrols">';
1329 echo '<div class="emailnotification">';
1330 echo '<label for="mailinfo">'.get_string('enableemailnotification','assignment').'</label>';
1331 echo '<input type="hidden" name="mailinfo" value="0" />';
1332 echo '<input type="checkbox" id="mailinfo" name="mailinfo" value="1" '.$lastmailinfo.' />';
1333 helpbutton('emailnotification', get_string('enableemailnotification', 'assignment'), 'assignment').'</p></div>';
1334 echo '</div>';
1335 echo '<div class="fastgbutton"><input type="submit" name="fastg" value="'.get_string('saveallfeedback', 'assignment').'" /></div>';
1336 echo '</div>';
1337 echo '</form>';
1339 /// End of fast grading form
1341 /// Mini form for setting user preference
1342 echo '<div class="qgprefs">';
1343 echo '<form id="options" action="submissions.php?id='.$this->cm->id.'" method="post"><div>';
1344 echo '<input type="hidden" name="updatepref" value="1" />';
1345 echo '<table id="optiontable">';
1346 echo '<tr><td>';
1347 echo '<label for="perpage">'.get_string('pagesize','assignment').'</label>';
1348 echo '</td>';
1349 echo '<td>';
1350 echo '<input type="text" id="perpage" name="perpage" size="1" value="'.$perpage.'" />';
1351 helpbutton('pagesize', get_string('pagesize','assignment'), 'assignment');
1352 echo '</td></tr>';
1353 echo '<tr><td>';
1354 echo '<label for="quickgrade">'.get_string('quickgrade','assignment').'</label>';
1355 echo '</td>';
1356 echo '<td>';
1357 $checked = $quickgrade ? 'checked="checked"' : '';
1358 echo '<input type="checkbox" id="quickgrade" name="quickgrade" value="1" '.$checked.' />';
1359 helpbutton('quickgrade', get_string('quickgrade', 'assignment'), 'assignment').'</p></div>';
1360 echo '</td></tr>';
1361 echo '<tr><td colspan="2">';
1362 echo '<input type="submit" value="'.get_string('savepreferences').'" />';
1363 echo '</td></tr></table>';
1364 echo '</div></form></div>';
1365 ///End of mini form
1366 print_footer($this->course);
1370 * Process teacher feedback submission
1372 * This is called by submissions() when a grading even has taken place.
1373 * It gets its data from the submitted form.
1374 * @return object The updated submission object
1376 function process_feedback() {
1377 global $CFG, $USER;
1378 require_once($CFG->libdir.'/gradelib.php');
1380 if (!$feedback = data_submitted() or !confirm_sesskey()) { // No incoming data?
1381 return false;
1384 ///For save and next, we need to know the userid to save, and the userid to go
1385 ///We use a new hidden field in the form, and set it to -1. If it's set, we use this
1386 ///as the userid to store
1387 if ((int)$feedback->saveuserid !== -1){
1388 $feedback->userid = $feedback->saveuserid;
1391 if (!empty($feedback->cancel)) { // User hit cancel button
1392 return false;
1395 $grading_info = grade_get_grades($this->course->id, 'mod', 'assignment', $this->assignment->id, $feedback->userid);
1397 // store outcomes if needed
1398 $this->process_outcomes($feedback->userid);
1400 $submission = $this->get_submission($feedback->userid, true); // Get or make one
1402 if (!$grading_info->items[0]->grades[$feedback->userid]->locked and
1403 !$grading_info->items[0]->grades[$feedback->userid]->overridden) {
1405 $submission->grade = $feedback->grade;
1406 $submission->submissioncomment = $feedback->submissioncomment;
1407 $submission->format = $feedback->format;
1408 $submission->teacher = $USER->id;
1409 $mailinfo = get_user_preferences('assignment_mailinfo', 0);
1410 if (!$mailinfo) {
1411 $submission->mailed = 1; // treat as already mailed
1412 } else {
1413 $submission->mailed = 0; // Make sure mail goes out (again, even)
1415 $submission->timemarked = time();
1417 unset($submission->data1); // Don't need to update this.
1418 unset($submission->data2); // Don't need to update this.
1420 if (empty($submission->timemodified)) { // eg for offline assignments
1421 // $submission->timemodified = time();
1424 if (! update_record('assignment_submissions', $submission)) {
1425 return false;
1428 // triger grade event
1429 $this->update_grade($submission);
1431 add_to_log($this->course->id, 'assignment', 'update grades',
1432 'submissions.php?id='.$this->assignment->id.'&user='.$feedback->userid, $feedback->userid, $this->cm->id);
1435 return $submission;
1439 function process_outcomes($userid) {
1440 global $CFG, $USER;
1442 if (empty($CFG->enableoutcomes)) {
1443 return;
1446 require_once($CFG->libdir.'/gradelib.php');
1448 if (!$formdata = data_submitted() or !confirm_sesskey()) {
1449 return;
1452 $data = array();
1453 $grading_info = grade_get_grades($this->course->id, 'mod', 'assignment', $this->assignment->id, $userid);
1455 if (!empty($grading_info->outcomes)) {
1456 foreach($grading_info->outcomes as $n=>$old) {
1457 $name = 'outcome_'.$n;
1458 if (isset($formdata->{$name}[$userid]) and $old->grades[$userid]->grade != $formdata->{$name}[$userid]) {
1459 $data[$n] = $formdata->{$name}[$userid];
1463 if (count($data) > 0) {
1464 grade_update_outcomes('mod/assignment', $this->course->id, 'mod', 'assignment', $this->assignment->id, $userid, $data);
1470 * Load the submission object for a particular user
1472 * @param $userid int The id of the user whose submission we want or 0 in which case USER->id is used
1473 * @param $createnew boolean optional Defaults to false. If set to true a new submission object will be created in the database
1474 * @param bool $teachermodified student submission set if false
1475 * @return object The submission
1477 function get_submission($userid=0, $createnew=false, $teachermodified=false) {
1478 global $USER;
1480 if (empty($userid)) {
1481 $userid = $USER->id;
1484 $submission = get_record('assignment_submissions', 'assignment', $this->assignment->id, 'userid', $userid);
1486 if ($submission || !$createnew) {
1487 return $submission;
1489 $newsubmission = $this->prepare_new_submission($userid, $teachermodified);
1490 if (!insert_record("assignment_submissions", $newsubmission)) {
1491 error("Could not insert a new empty submission");
1494 return get_record('assignment_submissions', 'assignment', $this->assignment->id, 'userid', $userid);
1498 * Instantiates a new submission object for a given user
1500 * Sets the assignment, userid and times, everything else is set to default values.
1501 * @param $userid int The userid for which we want a submission object
1502 * @param bool $teachermodified student submission set if false
1503 * @return object The submission
1505 function prepare_new_submission($userid, $teachermodified=false) {
1506 $submission = new Object;
1507 $submission->assignment = $this->assignment->id;
1508 $submission->userid = $userid;
1509 //$submission->timecreated = time();
1510 $submission->timecreated = '';
1511 // teachers should not be modifying modified date, except offline assignments
1512 if ($teachermodified) {
1513 $submission->timemodified = 0;
1514 } else {
1515 $submission->timemodified = $submission->timecreated;
1517 $submission->numfiles = 0;
1518 $submission->data1 = '';
1519 $submission->data2 = '';
1520 $submission->grade = -1;
1521 $submission->submissioncomment = '';
1522 $submission->format = 0;
1523 $submission->teacher = 0;
1524 $submission->timemarked = 0;
1525 $submission->mailed = 0;
1526 return $submission;
1530 * Return all assignment submissions by ENROLLED students (even empty)
1532 * @param $sort string optional field names for the ORDER BY in the sql query
1533 * @param $dir string optional specifying the sort direction, defaults to DESC
1534 * @return array The submission objects indexed by id
1536 function get_submissions($sort='', $dir='DESC') {
1537 return assignment_get_all_submissions($this->assignment, $sort, $dir);
1541 * Counts all real assignment submissions by ENROLLED students (not empty ones)
1543 * @param $groupid int optional If nonzero then count is restricted to this group
1544 * @return int The number of submissions
1546 function count_real_submissions($groupid=0) {
1547 return assignment_count_real_submissions($this->cm, $groupid);
1551 * Alerts teachers by email of new or changed assignments that need grading
1553 * First checks whether the option to email teachers is set for this assignment.
1554 * Sends an email to ALL teachers in the course (or in the group if using separate groups).
1555 * Uses the methods email_teachers_text() and email_teachers_html() to construct the content.
1556 * @param $submission object The submission that has changed
1558 function email_teachers($submission) {
1559 global $CFG;
1561 if (empty($this->assignment->emailteachers)) { // No need to do anything
1562 return;
1565 $user = get_record('user', 'id', $submission->userid);
1567 if ($teachers = $this->get_graders($user)) {
1569 $strassignments = get_string('modulenameplural', 'assignment');
1570 $strassignment = get_string('modulename', 'assignment');
1571 $strsubmitted = get_string('submitted', 'assignment');
1573 foreach ($teachers as $teacher) {
1574 $info = new object();
1575 $info->username = fullname($user, true);
1576 $info->assignment = format_string($this->assignment->name,true);
1577 $info->url = $CFG->wwwroot.'/mod/assignment/submissions.php?id='.$this->cm->id;
1579 $postsubject = $strsubmitted.': '.$info->username.' -> '.$this->assignment->name;
1580 $posttext = $this->email_teachers_text($info);
1581 $posthtml = ($teacher->mailformat == 1) ? $this->email_teachers_html($info) : '';
1583 @email_to_user($teacher, $user, $postsubject, $posttext, $posthtml); // If it fails, oh well, too bad.
1589 * Returns a list of teachers that should be grading given submission
1591 function get_graders($user) {
1592 //potential graders
1593 $potgraders = get_users_by_capability($this->context, 'mod/assignment:grade', '', '', '', '', '', '', false, false);
1595 $graders = array();
1596 if (groups_get_activity_groupmode($this->cm) == SEPARATEGROUPS) { // Separate groups are being used
1597 if ($groups = groups_get_all_groups($this->course->id, $user->id)) { // Try to find all groups
1598 foreach ($groups as $group) {
1599 foreach ($potgraders as $t) {
1600 if ($t->id == $user->id) {
1601 continue; // do not send self
1603 if (groups_is_member($group->id, $t->id)) {
1604 $graders[$t->id] = $t;
1608 } else {
1609 // user not in group, try to find graders without group
1610 foreach ($potgraders as $t) {
1611 if ($t->id == $user->id) {
1612 continue; // do not send self
1614 if (!groups_get_all_groups($this->course->id, $t->id)) { //ugly hack
1615 $graders[$t->id] = $t;
1619 } else {
1620 foreach ($potgraders as $t) {
1621 if ($t->id == $user->id) {
1622 continue; // do not send self
1624 $graders[$t->id] = $t;
1627 return $graders;
1631 * Creates the text content for emails to teachers
1633 * @param $info object The info used by the 'emailteachermail' language string
1634 * @return string
1636 function email_teachers_text($info) {
1637 $posttext = format_string($this->course->shortname).' -> '.$this->strassignments.' -> '.
1638 format_string($this->assignment->name)."\n";
1639 $posttext .= '---------------------------------------------------------------------'."\n";
1640 $posttext .= get_string("emailteachermail", "assignment", $info)."\n";
1641 $posttext .= "\n---------------------------------------------------------------------\n";
1642 return $posttext;
1646 * Creates the html content for emails to teachers
1648 * @param $info object The info used by the 'emailteachermailhtml' language string
1649 * @return string
1651 function email_teachers_html($info) {
1652 global $CFG;
1653 $posthtml = '<p><font face="sans-serif">'.
1654 '<a href="'.$CFG->wwwroot.'/course/view.php?id='.$this->course->id.'">'.format_string($this->course->shortname).'</a> ->'.
1655 '<a href="'.$CFG->wwwroot.'/mod/assignment/index.php?id='.$this->course->id.'">'.$this->strassignments.'</a> ->'.
1656 '<a href="'.$CFG->wwwroot.'/mod/assignment/view.php?id='.$this->cm->id.'">'.format_string($this->assignment->name).'</a></font></p>';
1657 $posthtml .= '<hr /><font face="sans-serif">';
1658 $posthtml .= '<p>'.get_string('emailteachermailhtml', 'assignment', $info).'</p>';
1659 $posthtml .= '</font><hr />';
1660 return $posthtml;
1664 * Produces a list of links to the files uploaded by a user
1666 * @param $userid int optional id of the user. If 0 then $USER->id is used.
1667 * @param $return boolean optional defaults to false. If true the list is returned rather than printed
1668 * @return string optional
1670 function print_user_files($userid=0, $return=false) {
1671 global $CFG, $USER;
1673 if (!$userid) {
1674 if (!isloggedin()) {
1675 return '';
1677 $userid = $USER->id;
1680 $filearea = $this->file_area_name($userid);
1682 $output = '';
1684 if ($basedir = $this->file_area($userid)) {
1685 if ($files = get_directory_list($basedir)) {
1686 require_once($CFG->libdir.'/filelib.php');
1687 foreach ($files as $key => $file) {
1689 $icon = mimeinfo('icon', $file);
1690 $ffurl = get_file_url("$filearea/$file", array('forcedownload'=>1));
1692 $output .= '<img src="'.$CFG->pixpath.'/f/'.$icon.'" class="icon" alt="'.$icon.'" />'.
1693 '<a href="'.$ffurl.'" >'.$file.'</a><br />';
1698 $output = '<div class="files">'.$output.'</div>';
1700 if ($return) {
1701 return $output;
1703 echo $output;
1707 * Count the files uploaded by a given user
1709 * @param $userid int The user id
1710 * @return int
1712 function count_user_files($userid) {
1713 global $CFG;
1715 $filearea = $this->file_area_name($userid);
1717 if ( is_dir($CFG->dataroot.'/'.$filearea) && $basedir = $this->file_area($userid)) {
1718 if ($files = get_directory_list($basedir)) {
1719 return count($files);
1722 return 0;
1726 * Creates a directory file name, suitable for make_upload_directory()
1728 * @param $userid int The user id
1729 * @return string path to file area
1731 function file_area_name($userid) {
1732 global $CFG;
1734 return $this->course->id.'/'.$CFG->moddata.'/assignment/'.$this->assignment->id.'/'.$userid;
1738 * Makes an upload directory
1740 * @param $userid int The user id
1741 * @return string path to file area.
1743 function file_area($userid) {
1744 return make_upload_directory( $this->file_area_name($userid) );
1748 * Returns true if the student is allowed to submit
1750 * Checks that the assignment has started and, if the option to prevent late
1751 * submissions is set, also checks that the assignment has not yet closed.
1752 * @return boolean
1754 function isopen() {
1755 $time = time();
1756 if ($this->assignment->preventlate && $this->assignment->timedue) {
1757 return ($this->assignment->timeavailable <= $time && $time <= $this->assignment->timedue);
1758 } else {
1759 return ($this->assignment->timeavailable <= $time);
1765 * Return true if is set description is hidden till available date
1767 * This is needed by calendar so that hidden descriptions do not
1768 * come up in upcoming events.
1770 * Check that description is hidden till available date
1771 * By default return false
1772 * Assignments types should implement this method if needed
1773 * @return boolen
1775 function description_is_hidden() {
1776 return false;
1780 * Return an outline of the user's interaction with the assignment
1782 * The default method prints the grade and timemodified
1783 * @param $grade object
1784 * @return object with properties ->info and ->time
1786 function user_outline($grade) {
1787 $result = new object();
1788 $result->info = get_string('grade').': '.$grade->str_long_grade;
1789 $result->time = $grade->dategraded;
1790 return $result;
1794 * Print complete information about the user's interaction with the assignment
1796 * @param $user object
1798 function user_complete($user, $grade=null) {
1799 if ($grade) {
1800 echo '<p>'.get_string('grade').': '.$grade->str_long_grade.'</p>';
1801 if ($grade->str_feedback) {
1802 echo '<p>'.get_string('feedback').': '.$grade->str_feedback.'</p>';
1806 if ($submission = $this->get_submission($user->id)) {
1807 if ($basedir = $this->file_area($user->id)) {
1808 if ($files = get_directory_list($basedir)) {
1809 $countfiles = count($files)." ".get_string("uploadedfiles", "assignment");
1810 foreach ($files as $file) {
1811 $countfiles .= "; $file";
1816 print_simple_box_start();
1817 echo get_string("lastmodified").": ";
1818 echo userdate($submission->timemodified);
1819 echo $this->display_lateness($submission->timemodified);
1821 $this->print_user_files($user->id);
1823 echo '<br />';
1825 $this->view_feedback($submission);
1827 print_simple_box_end();
1829 } else {
1830 print_string("notsubmittedyet", "assignment");
1835 * Return a string indicating how late a submission is
1837 * @param $timesubmitted int
1838 * @return string
1840 function display_lateness($timesubmitted) {
1841 return assignment_display_lateness($timesubmitted, $this->assignment->timedue);
1845 * Empty method stub for all delete actions.
1847 function delete() {
1848 //nothing by default
1849 redirect('view.php?id='.$this->cm->id);
1853 * Empty custom feedback grading form.
1855 function custom_feedbackform($submission, $return=false) {
1856 //nothing by default
1857 return '';
1861 * Add a get_coursemodule_info function in case any assignment type wants to add 'extra' information
1862 * for the course (see resource).
1864 * Given a course_module object, this function returns any "extra" information that may be needed
1865 * when printing this activity in a course listing. See get_array_of_activities() in course/lib.php.
1867 * @param $coursemodule object The coursemodule object (record).
1868 * @return object An object on information that the coures will know about (most noticeably, an icon).
1871 function get_coursemodule_info($coursemodule) {
1872 return false;
1876 * Plugin cron method - do not use $this here, create new assignment instances if needed.
1877 * @return void
1879 function cron() {
1880 //no plugin cron by default - override if needed
1884 * Reset all submissions
1886 function reset_userdata($data) {
1887 global $CFG;
1888 require_once($CFG->libdir.'/filelib.php');
1890 if (!count_records('assignment', 'course', $data->courseid, 'assignmenttype', $this->type)) {
1891 return array(); // no assignments of this type present
1894 $componentstr = get_string('modulenameplural', 'assignment');
1895 $status = array();
1897 $typestr = get_string('type'.$this->type, 'assignment');
1898 // ugly hack to support pluggable assignment type titles...
1899 if($typestr === '[[type'.$this->type.']]'){
1900 $typestr = get_string('type'.$this->type, 'assignment_'.$this->type);
1903 if (!empty($data->reset_assignment_submissions)) {
1904 $assignmentssql = "SELECT a.id
1905 FROM {$CFG->prefix}assignment a
1906 WHERE a.course={$data->courseid} AND a.assignmenttype='{$this->type}'";
1908 delete_records_select('assignment_submissions', "assignment IN ($assignmentssql)");
1910 if ($assignments = get_records_sql($assignmentssql)) {
1911 foreach ($assignments as $assignmentid=>$unused) {
1912 fulldelete($CFG->dataroot.'/'.$data->courseid.'/moddata/assignment/'.$assignmentid);
1916 $status[] = array('component'=>$componentstr, 'item'=>get_string('deleteallsubmissions','assignment').': '.$typestr, 'error'=>false);
1918 if (empty($data->reset_gradebook_grades)) {
1919 // remove all grades from gradebook
1920 assignment_reset_gradebook($data->courseid, $this->type);
1924 /// updating dates - shift may be negative too
1925 if ($data->timeshift) {
1926 shift_course_mod_dates('assignment', array('timedue', 'timeavailable'), $data->timeshift, $data->courseid);
1927 $status[] = array('component'=>$componentstr, 'item'=>get_string('datechanged').': '.$typestr, 'error'=>false);
1930 return $status;
1934 * base implementation for backing up subtype specific information
1935 * for one single module
1937 * @param filehandle $bf file handle for xml file to write to
1938 * @param mixed $preferences the complete backup preference object
1940 * @return boolean
1942 * @static
1944 function backup_one_mod($bf, $preferences, $assignment) {
1945 return true;
1949 * base implementation for backing up subtype specific information
1950 * for one single submission
1952 * @param filehandle $bf file handle for xml file to write to
1953 * @param mixed $preferences the complete backup preference object
1954 * @param object $submission the assignment submission db record
1956 * @return boolean
1958 * @static
1960 function backup_one_submission($bf, $preferences, $assignment, $submission) {
1961 return true;
1965 * base implementation for restoring subtype specific information
1966 * for one single module
1968 * @param array $info the array representing the xml
1969 * @param object $restore the restore preferences
1971 * @return boolean
1973 * @static
1975 function restore_one_mod($info, $restore, $assignment) {
1976 return true;
1980 * base implementation for restoring subtype specific information
1981 * for one single submission
1983 * @param object $submission the newly created submission
1984 * @param array $info the array representing the xml
1985 * @param object $restore the restore preferences
1987 * @return boolean
1989 * @static
1991 function restore_one_submission($info, $restore, $assignment, $submission) {
1992 return true;
1995 } ////// End of the assignment_base class
1999 /// OTHER STANDARD FUNCTIONS ////////////////////////////////////////////////////////
2002 * Deletes an assignment instance
2004 * This is done by calling the delete_instance() method of the assignment type class
2006 function assignment_delete_instance($id){
2007 global $CFG;
2009 if (! $assignment = get_record('assignment', 'id', $id)) {
2010 return false;
2013 // fall back to base class if plugin missing
2014 $classfile = "$CFG->dirroot/mod/assignment/type/$assignment->assignmenttype/assignment.class.php";
2015 if (file_exists($classfile)) {
2016 require_once($classfile);
2017 $assignmentclass = "assignment_$assignment->assignmenttype";
2019 } else {
2020 debugging("Missing assignment plug-in: {$assignment->assignmenttype}. Using base class for deleting instead.");
2021 $assignmentclass = "assignment_base";
2024 $ass = new $assignmentclass();
2025 return $ass->delete_instance($assignment);
2030 * Updates an assignment instance
2032 * This is done by calling the update_instance() method of the assignment type class
2034 function assignment_update_instance($assignment){
2035 global $CFG;
2037 $assignment->assignmenttype = clean_param($assignment->assignmenttype, PARAM_SAFEDIR);
2039 require_once("$CFG->dirroot/mod/assignment/type/$assignment->assignmenttype/assignment.class.php");
2040 $assignmentclass = "assignment_$assignment->assignmenttype";
2041 $ass = new $assignmentclass();
2042 return $ass->update_instance($assignment);
2047 * Adds an assignment instance
2049 * This is done by calling the add_instance() method of the assignment type class
2051 function assignment_add_instance($assignment) {
2052 global $CFG;
2054 $assignment->assignmenttype = clean_param($assignment->assignmenttype, PARAM_SAFEDIR);
2056 require_once("$CFG->dirroot/mod/assignment/type/$assignment->assignmenttype/assignment.class.php");
2057 $assignmentclass = "assignment_$assignment->assignmenttype";
2058 $ass = new $assignmentclass();
2059 return $ass->add_instance($assignment);
2064 * Returns an outline of a user interaction with an assignment
2066 * This is done by calling the user_outline() method of the assignment type class
2068 function assignment_user_outline($course, $user, $mod, $assignment) {
2069 global $CFG;
2071 require_once("$CFG->libdir/gradelib.php");
2072 require_once("$CFG->dirroot/mod/assignment/type/$assignment->assignmenttype/assignment.class.php");
2073 $assignmentclass = "assignment_$assignment->assignmenttype";
2074 $ass = new $assignmentclass($mod->id, $assignment, $mod, $course);
2075 $grades = grade_get_grades($course->id, 'mod', 'assignment', $assignment->id, $user->id);
2076 if (!empty($grades->items[0]->grades)) {
2077 return $ass->user_outline(reset($grades->items[0]->grades));
2078 } else {
2079 return null;
2084 * Prints the complete info about a user's interaction with an assignment
2086 * This is done by calling the user_complete() method of the assignment type class
2088 function assignment_user_complete($course, $user, $mod, $assignment) {
2089 global $CFG;
2091 require_once("$CFG->libdir/gradelib.php");
2092 require_once("$CFG->dirroot/mod/assignment/type/$assignment->assignmenttype/assignment.class.php");
2093 $assignmentclass = "assignment_$assignment->assignmenttype";
2094 $ass = new $assignmentclass($mod->id, $assignment, $mod, $course);
2095 $grades = grade_get_grades($course->id, 'mod', 'assignment', $assignment->id, $user->id);
2096 if (empty($grades->items[0]->grades)) {
2097 $grade = false;
2098 } else {
2099 $grade = reset($grades->items[0]->grades);
2101 return $ass->user_complete($user, $grade);
2105 * Function to be run periodically according to the moodle cron
2107 * Finds all assignment notifications that have yet to be mailed out, and mails them
2109 function assignment_cron () {
2111 global $CFG, $USER;
2113 /// first execute all crons in plugins
2114 if ($plugins = get_list_of_plugins('mod/assignment/type')) {
2115 foreach ($plugins as $plugin) {
2116 require_once("$CFG->dirroot/mod/assignment/type/$plugin/assignment.class.php");
2117 $assignmentclass = "assignment_$plugin";
2118 $ass = new $assignmentclass();
2119 $ass->cron();
2123 /// Notices older than 1 day will not be mailed. This is to avoid the problem where
2124 /// cron has not been running for a long time, and then suddenly people are flooded
2125 /// with mail from the past few weeks or months
2127 $timenow = time();
2128 $endtime = $timenow - $CFG->maxeditingtime;
2129 $starttime = $endtime - 24 * 3600; /// One day earlier
2131 if ($submissions = assignment_get_unmailed_submissions($starttime, $endtime)) {
2133 $realuser = clone($USER);
2135 foreach ($submissions as $key => $submission) {
2136 if (! set_field("assignment_submissions", "mailed", "1", "id", "$submission->id")) {
2137 echo "Could not update the mailed field for id $submission->id. Not mailed.\n";
2138 unset($submissions[$key]);
2142 $timenow = time();
2144 foreach ($submissions as $submission) {
2146 echo "Processing assignment submission $submission->id\n";
2148 if (! $user = get_record("user", "id", "$submission->userid")) {
2149 echo "Could not find user $post->userid\n";
2150 continue;
2153 if (! $course = get_record("course", "id", "$submission->course")) {
2154 echo "Could not find course $submission->course\n";
2155 continue;
2158 /// Override the language and timezone of the "current" user, so that
2159 /// mail is customised for the receiver.
2160 $USER = $user;
2161 course_setup($course);
2163 if (!has_capability('moodle/course:view', get_context_instance(CONTEXT_COURSE, $submission->course), $user->id)) {
2164 echo fullname($user)." not an active participant in " . format_string($course->shortname) . "\n";
2165 continue;
2168 if (! $teacher = get_record("user", "id", "$submission->teacher")) {
2169 echo "Could not find teacher $submission->teacher\n";
2170 continue;
2173 if (! $mod = get_coursemodule_from_instance("assignment", $submission->assignment, $course->id)) {
2174 echo "Could not find course module for assignment id $submission->assignment\n";
2175 continue;
2178 if (! $mod->visible) { /// Hold mail notification for hidden assignments until later
2179 continue;
2182 $strassignments = get_string("modulenameplural", "assignment");
2183 $strassignment = get_string("modulename", "assignment");
2185 $assignmentinfo = new object();
2186 $assignmentinfo->teacher = fullname($teacher);
2187 $assignmentinfo->assignment = format_string($submission->name,true);
2188 $assignmentinfo->url = "$CFG->wwwroot/mod/assignment/view.php?id=$mod->id";
2190 $postsubject = "$course->shortname: $strassignments: ".format_string($submission->name,true);
2191 $posttext = "$course->shortname -> $strassignments -> ".format_string($submission->name,true)."\n";
2192 $posttext .= "---------------------------------------------------------------------\n";
2193 $posttext .= get_string("assignmentmail", "assignment", $assignmentinfo)."\n";
2194 $posttext .= "---------------------------------------------------------------------\n";
2196 if ($user->mailformat == 1) { // HTML
2197 $posthtml = "<p><font face=\"sans-serif\">".
2198 "<a href=\"$CFG->wwwroot/course/view.php?id=$course->id\">$course->shortname</a> ->".
2199 "<a href=\"$CFG->wwwroot/mod/assignment/index.php?id=$course->id\">$strassignments</a> ->".
2200 "<a href=\"$CFG->wwwroot/mod/assignment/view.php?id=$mod->id\">".format_string($submission->name,true)."</a></font></p>";
2201 $posthtml .= "<hr /><font face=\"sans-serif\">";
2202 $posthtml .= "<p>".get_string("assignmentmailhtml", "assignment", $assignmentinfo)."</p>";
2203 $posthtml .= "</font><hr />";
2204 } else {
2205 $posthtml = "";
2208 if (! email_to_user($user, $teacher, $postsubject, $posttext, $posthtml)) {
2209 echo "Error: assignment cron: Could not send out mail for id $submission->id to user $user->id ($user->email)\n";
2213 $USER = $realuser;
2214 course_setup(SITEID); // reset cron user language, theme and timezone settings
2218 return true;
2222 * Return grade for given user or all users.
2224 * @param int $assignmentid id of assignment
2225 * @param int $userid optional user id, 0 means all users
2226 * @return array array of grades, false if none
2228 function assignment_get_user_grades($assignment, $userid=0) {
2229 global $CFG;
2231 $user = $userid ? "AND u.id = $userid" : "";
2233 $sql = "SELECT u.id, u.id AS userid, s.grade AS rawgrade, s.submissioncomment AS feedback, s.format AS feedbackformat,
2234 s.teacher AS usermodified, s.timemarked AS dategraded, s.timemodified AS datesubmitted
2235 FROM {$CFG->prefix}user u, {$CFG->prefix}assignment_submissions s
2236 WHERE u.id = s.userid AND s.assignment = $assignment->id
2237 $user";
2239 return get_records_sql($sql);
2243 * Update grades by firing grade_updated event
2245 * @param object $assignment null means all assignments
2246 * @param int $userid specific user only, 0 mean all
2248 function assignment_update_grades($assignment=null, $userid=0, $nullifnone=true) {
2249 global $CFG;
2250 if (!function_exists('grade_update')) { //workaround for buggy PHP versions
2251 require_once($CFG->libdir.'/gradelib.php');
2254 if ($assignment != null) {
2255 if ($grades = assignment_get_user_grades($assignment, $userid)) {
2256 foreach($grades as $k=>$v) {
2257 if ($v->rawgrade == -1) {
2258 $grades[$k]->rawgrade = null;
2261 assignment_grade_item_update($assignment, $grades);
2262 } else {
2263 assignment_grade_item_update($assignment);
2266 } else {
2267 $sql = "SELECT a.*, cm.idnumber as cmidnumber, a.course as courseid
2268 FROM {$CFG->prefix}assignment a, {$CFG->prefix}course_modules cm, {$CFG->prefix}modules m
2269 WHERE m.name='assignment' AND m.id=cm.module AND cm.instance=a.id";
2270 if ($rs = get_recordset_sql($sql)) {
2271 while ($assignment = rs_fetch_next_record($rs)) {
2272 if ($assignment->grade != 0) {
2273 assignment_update_grades($assignment);
2274 } else {
2275 assignment_grade_item_update($assignment);
2278 rs_close($rs);
2284 * Create grade item for given assignment
2286 * @param object $assignment object with extra cmidnumber
2287 * @param mixed optional array/object of grade(s); 'reset' means reset grades in gradebook
2288 * @return int 0 if ok, error code otherwise
2290 function assignment_grade_item_update($assignment, $grades=NULL) {
2291 global $CFG;
2292 if (!function_exists('grade_update')) { //workaround for buggy PHP versions
2293 require_once($CFG->libdir.'/gradelib.php');
2296 if (!isset($assignment->courseid)) {
2297 $assignment->courseid = $assignment->course;
2300 $params = array('itemname'=>$assignment->name, 'idnumber'=>$assignment->cmidnumber);
2302 if ($assignment->grade > 0) {
2303 $params['gradetype'] = GRADE_TYPE_VALUE;
2304 $params['grademax'] = $assignment->grade;
2305 $params['grademin'] = 0;
2307 } else if ($assignment->grade < 0) {
2308 $params['gradetype'] = GRADE_TYPE_SCALE;
2309 $params['scaleid'] = -$assignment->grade;
2311 } else {
2312 $params['gradetype'] = GRADE_TYPE_TEXT; // allow text comments only
2315 if ($grades === 'reset') {
2316 $params['reset'] = true;
2317 $grades = NULL;
2320 return grade_update('mod/assignment', $assignment->courseid, 'mod', 'assignment', $assignment->id, 0, $grades, $params);
2324 * Delete grade item for given assignment
2326 * @param object $assignment object
2327 * @return object assignment
2329 function assignment_grade_item_delete($assignment) {
2330 global $CFG;
2331 require_once($CFG->libdir.'/gradelib.php');
2333 if (!isset($assignment->courseid)) {
2334 $assignment->courseid = $assignment->course;
2337 return grade_update('mod/assignment', $assignment->courseid, 'mod', 'assignment', $assignment->id, 0, NULL, array('deleted'=>1));
2341 * Returns the users with data in one assignment (students and teachers)
2343 * @param $assignmentid int
2344 * @return array of user objects
2346 function assignment_get_participants($assignmentid) {
2348 global $CFG;
2350 //Get students
2351 $students = get_records_sql("SELECT DISTINCT u.id, u.id
2352 FROM {$CFG->prefix}user u,
2353 {$CFG->prefix}assignment_submissions a
2354 WHERE a.assignment = '$assignmentid' and
2355 u.id = a.userid");
2356 //Get teachers
2357 $teachers = get_records_sql("SELECT DISTINCT u.id, u.id
2358 FROM {$CFG->prefix}user u,
2359 {$CFG->prefix}assignment_submissions a
2360 WHERE a.assignment = '$assignmentid' and
2361 u.id = a.teacher");
2363 //Add teachers to students
2364 if ($teachers) {
2365 foreach ($teachers as $teacher) {
2366 $students[$teacher->id] = $teacher;
2369 //Return students array (it contains an array of unique users)
2370 return ($students);
2374 * Checks if a scale is being used by an assignment
2376 * This is used by the backup code to decide whether to back up a scale
2377 * @param $assignmentid int
2378 * @param $scaleid int
2379 * @return boolean True if the scale is used by the assignment
2381 function assignment_scale_used($assignmentid, $scaleid) {
2383 $return = false;
2385 $rec = get_record('assignment','id',$assignmentid,'grade',-$scaleid);
2387 if (!empty($rec) && !empty($scaleid)) {
2388 $return = true;
2391 return $return;
2395 * Checks if scale is being used by any instance of assignment
2397 * This is used to find out if scale used anywhere
2398 * @param $scaleid int
2399 * @return boolean True if the scale is used by any assignment
2401 function assignment_scale_used_anywhere($scaleid) {
2402 if ($scaleid and record_exists('assignment', 'grade', -$scaleid)) {
2403 return true;
2404 } else {
2405 return false;
2410 * Make sure up-to-date events are created for all assignment instances
2412 * This standard function will check all instances of this module
2413 * and make sure there are up-to-date events created for each of them.
2414 * If courseid = 0, then every assignment event in the site is checked, else
2415 * only assignment events belonging to the course specified are checked.
2416 * This function is used, in its new format, by restore_refresh_events()
2418 * @param $courseid int optional If zero then all assignments for all courses are covered
2419 * @return boolean Always returns true
2421 function assignment_refresh_events($courseid = 0) {
2423 if ($courseid == 0) {
2424 if (! $assignments = get_records("assignment")) {
2425 return true;
2427 } else {
2428 if (! $assignments = get_records("assignment", "course", $courseid)) {
2429 return true;
2432 $moduleid = get_field('modules', 'id', 'name', 'assignment');
2434 foreach ($assignments as $assignment) {
2435 $event = NULL;
2436 $event->name = addslashes($assignment->name);
2437 $event->description = addslashes($assignment->description);
2438 $event->timestart = $assignment->timedue;
2440 if ($event->id = get_field('event', 'id', 'modulename', 'assignment', 'instance', $assignment->id)) {
2441 update_event($event);
2443 } else {
2444 $event->courseid = $assignment->course;
2445 $event->groupid = 0;
2446 $event->userid = 0;
2447 $event->modulename = 'assignment';
2448 $event->instance = $assignment->id;
2449 $event->eventtype = 'due';
2450 $event->timeduration = 0;
2451 $event->visible = get_field('course_modules', 'visible', 'module', $moduleid, 'instance', $assignment->id);
2452 add_event($event);
2456 return true;
2460 * Print recent activity from all assignments in a given course
2462 * This is used by the recent activity block
2464 function assignment_print_recent_activity($course, $viewfullnames, $timestart) {
2465 global $CFG, $USER;
2467 // do not use log table if possible, it may be huge
2469 if (!$submissions = get_records_sql("SELECT asb.id, asb.timemodified, cm.id AS cmid, asb.userid,
2470 u.firstname, u.lastname, u.email, u.picture
2471 FROM {$CFG->prefix}assignment_submissions asb
2472 JOIN {$CFG->prefix}assignment a ON a.id = asb.assignment
2473 JOIN {$CFG->prefix}course_modules cm ON cm.instance = a.id
2474 JOIN {$CFG->prefix}modules md ON md.id = cm.module
2475 JOIN {$CFG->prefix}user u ON u.id = asb.userid
2476 WHERE asb.timemodified > $timestart AND
2477 a.course = {$course->id} AND
2478 md.name = 'assignment'
2479 ORDER BY asb.timemodified ASC")) {
2480 return false;
2483 $modinfo =& get_fast_modinfo($course); // reference needed because we might load the groups
2484 $show = array();
2485 $grader = array();
2487 foreach($submissions as $submission) {
2488 if (!array_key_exists($submission->cmid, $modinfo->cms)) {
2489 continue;
2491 $cm = $modinfo->cms[$submission->cmid];
2492 if (!$cm->uservisible) {
2493 continue;
2495 if ($submission->userid == $USER->id) {
2496 $show[] = $submission;
2497 continue;
2500 // the act of sumbitting of assignment may be considered private - only graders will see it if specified
2501 if (empty($CFG->assignment_showrecentsubmissions)) {
2502 if (!array_key_exists($cm->id, $grader)) {
2503 $grader[$cm->id] = has_capability('moodle/grade:viewall', get_context_instance(CONTEXT_MODULE, $cm->id));
2505 if (!$grader[$cm->id]) {
2506 continue;
2510 $groupmode = groups_get_activity_groupmode($cm, $course);
2512 if ($groupmode == SEPARATEGROUPS and !has_capability('moodle/site:accessallgroups', get_context_instance(CONTEXT_MODULE, $cm->id))) {
2513 if (isguestuser()) {
2514 // shortcut - guest user does not belong into any group
2515 continue;
2518 if (is_null($modinfo->groups)) {
2519 $modinfo->groups = groups_get_user_groups($course->id); // load all my groups and cache it in modinfo
2522 // this will be slow - show only users that share group with me in this cm
2523 if (empty($modinfo->groups[$cm->id])) {
2524 continue;
2526 $usersgroups = groups_get_all_groups($course->id, $cm->userid, $cm->groupingid);
2527 if (is_array($usersgroups)) {
2528 $usersgroups = array_keys($usersgroups);
2529 $interset = array_intersect($usersgroups, $modinfo->groups[$cm->id]);
2530 if (empty($intersect)) {
2531 continue;
2535 $show[] = $submission;
2538 if (empty($show)) {
2539 return false;
2542 print_headline(get_string('newsubmissions', 'assignment').':');
2544 foreach ($show as $submission) {
2545 $cm = $modinfo->cms[$submission->cmid];
2546 $link = $CFG->wwwroot.'/mod/assignment/view.php?id='.$cm->id;
2547 print_recent_activity_note($submission->timemodified, $submission, $cm->name, $link, false, $viewfullnames);
2550 return true;
2555 * Returns all assignments since a given time in specified forum.
2557 function assignment_get_recent_mod_activity(&$activities, &$index, $timestart, $courseid, $cmid, $userid=0, $groupid=0) {
2559 global $CFG, $COURSE, $USER;
2561 if ($COURSE->id == $courseid) {
2562 $course = $COURSE;
2563 } else {
2564 $course = get_record('course', 'id', $courseid);
2567 $modinfo =& get_fast_modinfo($course);
2569 $cm = $modinfo->cms[$cmid];
2571 if ($userid) {
2572 $userselect = "AND u.id = $userid";
2573 } else {
2574 $userselect = "";
2577 if ($groupid) {
2578 $groupselect = "AND gm.groupid = $groupid";
2579 $groupjoin = "JOIN {$CFG->prefix}groups_members gm ON gm.userid=u.id";
2580 } else {
2581 $groupselect = "";
2582 $groupjoin = "";
2585 if (!$submissions = get_records_sql("SELECT asb.id, asb.timemodified, asb.userid,
2586 u.firstname, u.lastname, u.email, u.picture
2587 FROM {$CFG->prefix}assignment_submissions asb
2588 JOIN {$CFG->prefix}assignment a ON a.id = asb.assignment
2589 JOIN {$CFG->prefix}user u ON u.id = asb.userid
2590 $groupjoin
2591 WHERE asb.timemodified > $timestart AND a.id = $cm->instance
2592 $userselect $groupselect
2593 ORDER BY asb.timemodified ASC")) {
2594 return;
2597 $groupmode = groups_get_activity_groupmode($cm, $course);
2598 $cm_context = get_context_instance(CONTEXT_MODULE, $cm->id);
2599 $grader = has_capability('moodle/grade:viewall', $cm_context);
2600 $accessallgroups = has_capability('moodle/site:accessallgroups', $cm_context);
2601 $viewfullnames = has_capability('moodle/site:viewfullnames', $cm_context);
2603 if (is_null($modinfo->groups)) {
2604 $modinfo->groups = groups_get_user_groups($course->id); // load all my groups and cache it in modinfo
2607 $show = array();
2609 foreach($submissions as $submission) {
2610 if ($submission->userid == $USER->id) {
2611 $show[] = $submission;
2612 continue;
2614 // the act of submitting of assignment may be considered private - only graders will see it if specified
2615 if (empty($CFG->assignment_showrecentsubmissions)) {
2616 if (!$grader) {
2617 continue;
2621 if ($groupmode == SEPARATEGROUPS and !$accessallgroups) {
2622 if (isguestuser()) {
2623 // shortcut - guest user does not belong into any group
2624 continue;
2627 // this will be slow - show only users that share group with me in this cm
2628 if (empty($modinfo->groups[$cm->id])) {
2629 continue;
2631 $usersgroups = groups_get_all_groups($course->id, $cm->userid, $cm->groupingid);
2632 if (is_array($usersgroups)) {
2633 $usersgroups = array_keys($usersgroups);
2634 $interset = array_intersect($usersgroups, $modinfo->groups[$cm->id]);
2635 if (empty($intersect)) {
2636 continue;
2640 $show[] = $submission;
2643 if (empty($show)) {
2644 return;
2647 if ($grader) {
2648 require_once($CFG->libdir.'/gradelib.php');
2649 $userids = array();
2650 foreach ($show as $id=>$submission) {
2651 $userids[] = $submission->userid;
2654 $grades = grade_get_grades($courseid, 'mod', 'assignment', $cm->instance, $userids);
2657 $aname = format_string($cm->name,true);
2658 foreach ($show as $submission) {
2659 $tmpactivity = new object();
2661 $tmpactivity->type = 'assignment';
2662 $tmpactivity->cmid = $cm->id;
2663 $tmpactivity->name = $aname;
2664 $tmpactivity->sectionnum = $cm->sectionnum;
2665 $tmpactivity->timestamp = $submission->timemodified;
2667 if ($grader) {
2668 $tmpactivity->grade = $grades->items[0]->grades[$submission->userid]->str_long_grade;
2671 $tmpactivity->user->userid = $submission->userid;
2672 $tmpactivity->user->fullname = fullname($submission, $viewfullnames);
2673 $tmpactivity->user->picture = $submission->picture;
2675 $activities[$index++] = $tmpactivity;
2678 return;
2682 * Print recent activity from all assignments in a given course
2684 * This is used by course/recent.php
2686 function assignment_print_recent_mod_activity($activity, $courseid, $detail, $modnames) {
2687 global $CFG;
2689 echo '<table border="0" cellpadding="3" cellspacing="0" class="assignment-recent">';
2691 echo "<tr><td class=\"userpicture\" valign=\"top\">";
2692 print_user_picture($activity->user->userid, $courseid, $activity->user->picture);
2693 echo "</td><td>";
2695 if ($detail) {
2696 $modname = $modnames[$activity->type];
2697 echo '<div class="title">';
2698 echo "<img src=\"$CFG->modpixpath/assignment/icon.gif\" ".
2699 "class=\"icon\" alt=\"$modname\">";
2700 echo "<a href=\"$CFG->wwwroot/mod/assignment/view.php?id={$activity->cmid}\">{$activity->name}</a>";
2701 echo '</div>';
2704 if (isset($activity->grade)) {
2705 echo '<div class="grade">';
2706 echo get_string('grade').': ';
2707 echo $activity->grade;
2708 echo '</div>';
2711 echo '<div class="user">';
2712 echo "<a href=\"$CFG->wwwroot/user/view.php?id={$activity->user->userid}&amp;course=$courseid\">"
2713 ."{$activity->user->fullname}</a> - ".userdate($activity->timestamp);
2714 echo '</div>';
2716 echo "</td></tr></table>";
2719 /// GENERIC SQL FUNCTIONS
2722 * Fetch info from logs
2724 * @param $log object with properties ->info (the assignment id) and ->userid
2725 * @return array with assignment name and user firstname and lastname
2727 function assignment_log_info($log) {
2728 global $CFG;
2729 return get_record_sql("SELECT a.name, u.firstname, u.lastname
2730 FROM {$CFG->prefix}assignment a,
2731 {$CFG->prefix}user u
2732 WHERE a.id = '$log->info'
2733 AND u.id = '$log->userid'");
2737 * Return list of marked submissions that have not been mailed out for currently enrolled students
2739 * @return array
2741 function assignment_get_unmailed_submissions($starttime, $endtime) {
2743 global $CFG;
2745 return get_records_sql("SELECT s.*, a.course, a.name
2746 FROM {$CFG->prefix}assignment_submissions s,
2747 {$CFG->prefix}assignment a
2748 WHERE s.mailed = 0
2749 AND s.timemarked <= $endtime
2750 AND s.timemarked >= $starttime
2751 AND s.assignment = a.id");
2753 /* return get_records_sql("SELECT s.*, a.course, a.name
2754 FROM {$CFG->prefix}assignment_submissions s,
2755 {$CFG->prefix}assignment a,
2756 {$CFG->prefix}user_students us
2757 WHERE s.mailed = 0
2758 AND s.timemarked <= $endtime
2759 AND s.timemarked >= $starttime
2760 AND s.assignment = a.id
2761 AND s.userid = us.userid
2762 AND a.course = us.course");
2767 * Counts all real assignment submissions by ENROLLED students (not empty ones)
2769 * There are also assignment type methods count_real_submissions() wich in the default
2770 * implementation simply call this function.
2771 * @param $groupid int optional If nonzero then count is restricted to this group
2772 * @return int The number of submissions
2774 function assignment_count_real_submissions($cm, $groupid=0) {
2775 global $CFG;
2777 $context = get_context_instance(CONTEXT_MODULE, $cm->id);
2779 // this is all the users with this capability set, in this context or higher
2780 if ($users = get_users_by_capability($context, 'mod/assignment:submit', 'u.id', '', '', '', $groupid, '', false)) {
2781 $users = array_keys($users);
2784 // if groupmembersonly used, remove users who are not in any group
2785 if ($users and !empty($CFG->enablegroupings) and $cm->groupmembersonly) {
2786 if ($groupingusers = groups_get_grouping_members($cm->groupingid, 'u.id', 'u.id')) {
2787 $users = array_intersect($users, array_keys($groupingusers));
2791 if (empty($users)) {
2792 return 0;
2795 $userlists = implode(',', $users);
2797 return count_records_sql("SELECT COUNT('x')
2798 FROM {$CFG->prefix}assignment_submissions
2799 WHERE assignment = $cm->instance AND
2800 timemodified > 0 AND
2801 userid IN ($userlists)");
2806 * Return all assignment submissions by ENROLLED students (even empty)
2808 * There are also assignment type methods get_submissions() wich in the default
2809 * implementation simply call this function.
2810 * @param $sort string optional field names for the ORDER BY in the sql query
2811 * @param $dir string optional specifying the sort direction, defaults to DESC
2812 * @return array The submission objects indexed by id
2814 function assignment_get_all_submissions($assignment, $sort="", $dir="DESC") {
2815 /// Return all assignment submissions by ENROLLED students (even empty)
2816 global $CFG;
2818 if ($sort == "lastname" or $sort == "firstname") {
2819 $sort = "u.$sort $dir";
2820 } else if (empty($sort)) {
2821 $sort = "a.timemodified DESC";
2822 } else {
2823 $sort = "a.$sort $dir";
2826 /* not sure this is needed at all since assignmenet already has a course define, so this join?
2827 $select = "s.course = '$assignment->course' AND";
2828 if ($assignment->course == SITEID) {
2829 $select = '';
2832 return get_records_sql("SELECT a.*
2833 FROM {$CFG->prefix}assignment_submissions a,
2834 {$CFG->prefix}user u
2835 WHERE u.id = a.userid
2836 AND a.assignment = '$assignment->id'
2837 ORDER BY $sort");
2839 /* return get_records_sql("SELECT a.*
2840 FROM {$CFG->prefix}assignment_submissions a,
2841 {$CFG->prefix}user_students s,
2842 {$CFG->prefix}user u
2843 WHERE a.userid = s.userid
2844 AND u.id = a.userid
2845 AND $select a.assignment = '$assignment->id'
2846 ORDER BY $sort");
2851 * Add a get_coursemodule_info function in case any assignment type wants to add 'extra' information
2852 * for the course (see resource).
2854 * Given a course_module object, this function returns any "extra" information that may be needed
2855 * when printing this activity in a course listing. See get_array_of_activities() in course/lib.php.
2857 * @param $coursemodule object The coursemodule object (record).
2858 * @return object An object on information that the coures will know about (most noticeably, an icon).
2861 function assignment_get_coursemodule_info($coursemodule) {
2862 global $CFG;
2864 if (! $assignment = get_record('assignment', 'id', $coursemodule->instance, '', '', '', '', 'id, assignmenttype, name')) {
2865 return false;
2868 $libfile = "$CFG->dirroot/mod/assignment/type/$assignment->assignmenttype/assignment.class.php";
2870 if (file_exists($libfile)) {
2871 require_once($libfile);
2872 $assignmentclass = "assignment_$assignment->assignmenttype";
2873 $ass = new $assignmentclass('staticonly');
2874 if ($result = $ass->get_coursemodule_info($coursemodule)) {
2875 return $result;
2876 } else {
2877 $info = new object();
2878 $info->name = $assignment->name;
2879 return $info;
2882 } else {
2883 debugging('Incorrect assignment type: '.$assignment->assignmenttype);
2884 return false;
2890 /// OTHER GENERAL FUNCTIONS FOR ASSIGNMENTS ///////////////////////////////////////
2893 * Returns an array of installed assignment types indexed and sorted by name
2895 * @return array The index is the name of the assignment type, the value its full name from the language strings
2897 function assignment_types() {
2898 $types = array();
2899 $names = get_list_of_plugins('mod/assignment/type');
2900 foreach ($names as $name) {
2901 $types[$name] = get_string('type'.$name, 'assignment');
2903 // ugly hack to support pluggable assignment type titles..
2904 if ($types[$name] == '[[type'.$name.']]') {
2905 $types[$name] = get_string('type'.$name, 'assignment_'.$name);
2908 asort($types);
2909 return $types;
2913 * Executes upgrade scripts for assignment types when necessary
2915 function assignment_upgrade_submodules() {
2917 global $CFG;
2919 /// Install/upgrade assignment types (it uses, simply, the standard plugin architecture)
2920 upgrade_plugins('assignment_type', 'mod/assignment/type', "$CFG->wwwroot/$CFG->admin/index.php");
2924 function assignment_print_overview($courses, &$htmlarray) {
2926 global $USER, $CFG;
2928 if (empty($courses) || !is_array($courses) || count($courses) == 0) {
2929 return array();
2932 if (!$assignments = get_all_instances_in_courses('assignment',$courses)) {
2933 return;
2936 $assignmentids = array();
2938 // Do assignment_base::isopen() here without loading the whole thing for speed
2939 foreach ($assignments as $key => $assignment) {
2940 $time = time();
2941 if ($assignment->timedue) {
2942 if ($assignment->preventlate) {
2943 $isopen = ($assignment->timeavailable <= $time && $time <= $assignment->timedue);
2944 } else {
2945 $isopen = ($assignment->timeavailable <= $time);
2948 if (empty($isopen) || empty($assignment->timedue)) {
2949 unset($assignments[$key]);
2950 }else{
2951 $assignmentids[] = $assignment->id;
2955 if(empty($assignmentids)){
2956 // no assigments to look at - we're done
2957 return true;
2960 $strduedate = get_string('duedate', 'assignment');
2961 $strduedateno = get_string('duedateno', 'assignment');
2962 $strgraded = get_string('graded', 'assignment');
2963 $strnotgradedyet = get_string('notgradedyet', 'assignment');
2964 $strnotsubmittedyet = get_string('notsubmittedyet', 'assignment');
2965 $strsubmitted = get_string('submitted', 'assignment');
2966 $strassignment = get_string('modulename', 'assignment');
2967 $strreviewed = get_string('reviewed','assignment');
2970 // NOTE: we do all possible database work here *outside* of the loop to ensure this scales
2972 // build up and array of unmarked submissions indexed by assigment id/ userid
2973 // for use where the user has grading rights on assigment
2974 $rs = get_recordset_sql("SELECT id, assignment, userid
2975 FROM {$CFG->prefix}assignment_submissions
2976 WHERE teacher = 0 AND timemarked = 0
2977 AND assignment IN (". implode(',', $assignmentids).")");
2979 $unmarkedsubmissions = array();
2980 while ($ra = rs_fetch_next_record($rs)) {
2981 $unmarkedsubmissions[$ra->assignment][$ra->userid] = $ra->id;
2983 rs_close($rs);
2986 // get all user submissions, indexed by assigment id
2987 $mysubmissions = get_records_sql("SELECT assignment, timemarked, teacher, grade
2988 FROM {$CFG->prefix}assignment_submissions
2989 WHERE userid = {$USER->id} AND
2990 assignment IN (".implode(',', $assignmentids).")");
2992 foreach ($assignments as $assignment) {
2993 $str = '<div class="assignment overview"><div class="name">'.$strassignment. ': '.
2994 '<a '.($assignment->visible ? '':' class="dimmed"').
2995 'title="'.$strassignment.'" href="'.$CFG->wwwroot.
2996 '/mod/assignment/view.php?id='.$assignment->coursemodule.'">'.
2997 $assignment->name.'</a></div>';
2998 if ($assignment->timedue) {
2999 $str .= '<div class="info">'.$strduedate.': '.userdate($assignment->timedue).'</div>';
3000 } else {
3001 $str .= '<div class="info">'.$strduedateno.'</div>';
3003 $context = get_context_instance(CONTEXT_MODULE, $assignment->coursemodule);
3004 if (has_capability('mod/assignment:grade', $context)) {
3006 // count how many people can submit
3007 $submissions = 0; // init
3008 if ($students = get_users_by_capability($context, 'mod/assignment:submit', 'u.id', '', '', '', 0, '', false)) {
3009 foreach($students as $student){
3010 if(isset($unmarkedsubmissions[$assignment->id][$student->id])){
3011 $submissions++;
3016 if ($submissions) {
3017 $str .= get_string('submissionsnotgraded', 'assignment', $submissions);
3019 } else {
3020 if(isset($mysubmissions[$assignment->id])){
3022 $submission = $mysubmissions[$assignment->id];
3024 if ($submission->teacher == 0 && $submission->timemarked == 0) {
3025 $str .= $strsubmitted . ', ' . $strnotgradedyet;
3026 } else if ($submission->grade <= 0) {
3027 $str .= $strsubmitted . ', ' . $strreviewed;
3028 } else {
3029 $str .= $strsubmitted . ', ' . $strgraded;
3031 } else {
3032 $str .= $strnotsubmittedyet . ' ' . assignment_display_lateness(time(), $assignment->timedue);
3035 $str .= '</div>';
3036 if (empty($htmlarray[$assignment->course]['assignment'])) {
3037 $htmlarray[$assignment->course]['assignment'] = $str;
3038 } else {
3039 $htmlarray[$assignment->course]['assignment'] .= $str;
3044 function assignment_display_lateness($timesubmitted, $timedue) {
3045 if (!$timedue) {
3046 return '';
3048 $time = $timedue - $timesubmitted;
3049 if ($time < 0) {
3050 $timetext = get_string('late', 'assignment', format_time($time));
3051 return ' (<span class="late">'.$timetext.'</span>)';
3052 } else {
3053 $timetext = get_string('early', 'assignment', format_time($time));
3054 return ' (<span class="early">'.$timetext.'</span>)';
3058 function assignment_get_view_actions() {
3059 return array('view');
3062 function assignment_get_post_actions() {
3063 return array('upload');
3066 function assignment_get_types() {
3067 global $CFG;
3068 $types = array();
3070 $type = new object();
3071 $type->modclass = MOD_CLASS_ACTIVITY;
3072 $type->type = "assignment_group_start";
3073 $type->typestr = '--'.get_string('modulenameplural', 'assignment');
3074 $types[] = $type;
3076 $standardassignments = array('upload','online','uploadsingle','offline');
3077 foreach ($standardassignments as $assignmenttype) {
3078 $type = new object();
3079 $type->modclass = MOD_CLASS_ACTIVITY;
3080 $type->type = "assignment&amp;type=$assignmenttype";
3081 $type->typestr = get_string("type$assignmenttype", 'assignment');
3082 $types[] = $type;
3085 /// Drop-in extra assignment types
3086 $assignmenttypes = get_list_of_plugins('mod/assignment/type');
3087 foreach ($assignmenttypes as $assignmenttype) {
3088 if (!empty($CFG->{'assignment_hide_'.$assignmenttype})) { // Not wanted
3089 continue;
3091 if (!in_array($assignmenttype, $standardassignments)) {
3092 $type = new object();
3093 $type->modclass = MOD_CLASS_ACTIVITY;
3094 $type->type = "assignment&amp;type=$assignmenttype";
3095 $type->typestr = get_string("type$assignmenttype", 'assignment_'.$assignmenttype);
3096 $types[] = $type;
3100 $type = new object();
3101 $type->modclass = MOD_CLASS_ACTIVITY;
3102 $type->type = "assignment_group_end";
3103 $type->typestr = '--';
3104 $types[] = $type;
3106 return $types;
3110 * Removes all grades from gradebook
3111 * @param int $courseid
3112 * @param string optional type
3114 function assignment_reset_gradebook($courseid, $type='') {
3115 global $CFG;
3117 $type = $type ? "AND a.assignmenttype='$type'" : '';
3119 $sql = "SELECT a.*, cm.idnumber as cmidnumber, a.course as courseid
3120 FROM {$CFG->prefix}assignment a, {$CFG->prefix}course_modules cm, {$CFG->prefix}modules m
3121 WHERE m.name='assignment' AND m.id=cm.module AND cm.instance=a.id AND a.course=$courseid $type";
3123 if ($assignments = get_records_sql($sql)) {
3124 foreach ($assignments as $assignment) {
3125 assignment_grade_item_update($assignment, 'reset');
3131 * This function is used by the reset_course_userdata function in moodlelib.
3132 * This function will remove all posts from the specified assignment
3133 * and clean up any related data.
3134 * @param $data the data submitted from the reset course.
3135 * @return array status array
3137 function assignment_reset_userdata($data) {
3138 global $CFG;
3140 $status = array();
3142 foreach (get_list_of_plugins('mod/assignment/type') as $type) {
3143 require_once("$CFG->dirroot/mod/assignment/type/$type/assignment.class.php");
3144 $assignmentclass = "assignment_$type";
3145 $ass = new $assignmentclass();
3146 $status = array_merge($status, $ass->reset_userdata($data));
3149 return $status;
3153 * Implementation of the function for printing the form elements that control
3154 * whether the course reset functionality affects the assignment.
3155 * @param $mform form passed by reference
3157 function assignment_reset_course_form_definition(&$mform) {
3158 $mform->addElement('header', 'assignmentheader', get_string('modulenameplural', 'assignment'));
3159 $mform->addElement('advcheckbox', 'reset_assignment_submissions', get_string('deleteallsubmissions','assignment'));
3163 * Course reset form defaults.
3165 function assignment_reset_course_form_defaults($course) {
3166 return array('reset_assignment_submissions'=>1);
3170 * Returns all other caps used in module
3172 function assignment_get_extra_capabilities() {
3173 return array('moodle/site:accessallgroups', 'moodle/site:viewfullnames');