MDL-10092:
[moodle-linuxchix.git] / mod / assignment / lib.php
blobb9f1e754449b80d78454292f5b673aab48097467
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 if (!isset($CFG->assignment_maxbytes)) {
12 set_config("assignment_maxbytes", 1024000); // Default maximum size for all assignments
14 if (!isset($CFG->assignment_itemstocount)) {
15 set_config("assignment_itemstocount", ASSIGNMENT_COUNT_WORDS); // Default item to count
18 /**
19 * Standard base class for all assignment submodules (assignment types).
21 class assignment_base {
23 var $cm;
24 var $course;
25 var $assignment;
26 var $strassignment;
27 var $strassignments;
28 var $strsubmissions;
29 var $strlastmodified;
30 var $navigation;
31 var $pagetitle;
32 var $currentgroup;
33 var $usehtmleditor;
34 var $defaultformat;
35 var $context;
36 var $lockedgrades;
38 /**
39 * Constructor for the base assignment class
41 * Constructor for the base assignment class.
42 * If cmid is set create the cm, course, assignment objects.
43 * If the assignment is hidden and the user is not a teacher then
44 * this prints a page header and notice.
46 * @param cmid integer, the current course module id - not set for new assignments
47 * @param assignment object, usually null, but if we have it we pass it to save db access
48 * @param cm object, usually null, but if we have it we pass it to save db access
49 * @param course object, usually null, but if we have it we pass it to save db access
51 function assignment_base($cmid='staticonly', $assignment=NULL, $cm=NULL, $course=NULL) {
52 if ($cmid == 'staticonly') {
53 //use static functions only!
54 return;
57 global $CFG;
59 if ($cm) {
60 $this->cm = $cm;
61 } else if (! $this->cm = get_coursemodule_from_id('assignment', $cmid)) {
62 error('Course Module ID was incorrect');
65 $this->context = get_context_instance(CONTEXT_MODULE,$this->cm->id);
67 if ($course) {
68 $this->course = $course;
69 } else if (! $this->course = get_record('course', 'id', $this->cm->course)) {
70 error('Course is misconfigured');
73 if ($assignment) {
74 $this->assignment = $assignment;
75 } else if (! $this->assignment = get_record('assignment', 'id', $this->cm->instance)) {
76 error('assignment ID was incorrect');
79 $this->assignment->cmidnumber = $this->cm->id; // compatibility with modedit assignment obj
80 $this->assignment->courseid = $this->course->id; // compatibility with modedit assignment obj
82 require_once($CFG->libdir.'/gradelib.php');
83 $this->lockedgrades = grade_is_locked($this->course->id, 'mod', 'assignment', $this->assignment->id, 0);
85 $this->strassignment = get_string('modulename', 'assignment');
86 $this->strassignments = get_string('modulenameplural', 'assignment');
87 $this->strsubmissions = get_string('submissions', 'assignment');
88 $this->strlastmodified = get_string('lastmodified');
90 $this->navigation[] = array('name' => $this->strassignments, 'link' => "index.php?id={$this->course->id}", 'type' => 'activity');
92 $this->pagetitle = strip_tags($this->course->shortname.': '.$this->strassignment.': '.format_string($this->assignment->name,true));
94 // visibility
95 $context = get_context_instance(CONTEXT_MODULE, $cmid);
96 if (!$this->cm->visible and !has_capability('moodle/course:viewhiddenactivities', $context)) {
97 $pagetitle = strip_tags($this->course->shortname.': '.$this->strassignment);
98 $this->navigation[] = array('name' => $this->strassignment, 'link' => '', 'type' => 'activityinstance');
99 $navigation = build_navigation($this->navigation);
101 print_header($pagetitle, $this->course->fullname, $this->navigation,
102 "", "", true, '', navmenu($this->course, $this->cm));
103 notice(get_string("activityiscurrentlyhidden"), "$CFG->wwwroot/course/view.php?id={$this->course->id}");
105 $this->currentgroup = groups_get_activity_group($this->cm);
107 /// Set up things for a HTML editor if it's needed
108 if ($this->usehtmleditor = can_use_html_editor()) {
109 $this->defaultformat = FORMAT_HTML;
110 } else {
111 $this->defaultformat = FORMAT_MOODLE;
116 * Display the assignment, used by view.php
118 * This in turn calls the methods producing individual parts of the page
120 function view() {
122 $context = get_context_instance(CONTEXT_MODULE,$this->cm->id);
123 require_capability('mod/assignment:view', $context);
125 add_to_log($this->course->id, "assignment", "view", "view.php?id={$this->cm->id}",
126 $this->assignment->id, $this->cm->id);
128 $this->view_header();
130 $this->view_intro();
132 $this->view_dates();
134 $this->view_feedback();
136 $this->view_footer();
140 * Display the header and top of a page
142 * (this doesn't change much for assignment types)
143 * This is used by the view() method to print the header of view.php but
144 * it can be used on other pages in which case the string to denote the
145 * page in the navigation trail should be passed as an argument
147 * @param $subpage string Description of subpage to be used in navigation trail
149 function view_header($subpage='') {
151 global $CFG;
154 if ($subpage) {
155 $this->navigation[] = array('name' => format_string($this->assignment->name,true), 'link' => "view.php?id={$this->cm->id}", 'type' => 'activityinstance');
156 $this->navigation[] = array('name' => $subpage, 'link' => '', 'type' => 'title');
157 } else {
158 $this->navigation[] = array('name' => format_string($this->assignment->name,true), 'link' => '', 'type' => 'activityinstance');
161 $navigation = build_navigation($this->navigation);
163 print_header($this->pagetitle, $this->course->fullname, $navigation, '', '',
164 true, update_module_button($this->cm->id, $this->course->id, $this->strassignment),
165 navmenu($this->course, $this->cm));
167 $groupmode = groups_get_activity_groupmode($this->cm);
168 $currentgroup = groups_get_activity_group($this->cm);
169 groups_print_activity_menu($this->cm, 'view.php?id=' . $this->cm->id);
171 echo '<div class="reportlink">'.$this->submittedlink().'</div>';
172 echo '<div class="clearer"></div>';
177 * Display the assignment intro
179 * This will most likely be extended by assignment type plug-ins
180 * The default implementation prints the assignment description in a box
182 function view_intro() {
183 print_simple_box_start('center', '', '', 0, 'generalbox', 'intro');
184 $formatoptions = new stdClass;
185 $formatoptions->noclean = true;
186 echo format_text($this->assignment->description, $this->assignment->format, $formatoptions);
187 print_simple_box_end();
191 * Display the assignment dates
193 * Prints the assignment start and end dates in a box.
194 * This will be suitable for most assignment types
196 function view_dates() {
197 if (!$this->assignment->timeavailable && !$this->assignment->timedue) {
198 return;
201 print_simple_box_start('center', '', '', 0, 'generalbox', 'dates');
202 echo '<table>';
203 if ($this->assignment->timeavailable) {
204 echo '<tr><td class="c0">'.get_string('availabledate','assignment').':</td>';
205 echo ' <td class="c1">'.userdate($this->assignment->timeavailable).'</td></tr>';
207 if ($this->assignment->timedue) {
208 echo '<tr><td class="c0">'.get_string('duedate','assignment').':</td>';
209 echo ' <td class="c1">'.userdate($this->assignment->timedue).'</td></tr>';
211 echo '</table>';
212 print_simple_box_end();
217 * Display the bottom and footer of a page
219 * This default method just prints the footer.
220 * This will be suitable for most assignment types
222 function view_footer() {
223 print_footer($this->course);
227 * Display the feedback to the student
229 * This default method prints the teacher picture and name, date when marked,
230 * grade and teacher submissioncomment.
232 * @param $submission object The submission object or NULL in which case it will be loaded
234 function view_feedback($submission=NULL) {
235 global $USER;
237 if (!$submission) { /// Get submission for this assignment
238 $submission = $this->get_submission($USER->id);
241 if (empty($submission->timemarked)) { /// Nothing to show, so print nothing
242 return;
245 /// We need the teacher info
246 if (! $teacher = get_record('user', 'id', $submission->teacher)) {
247 error('Could not find the teacher');
250 /// Print the feedback
251 print_heading(get_string('feedbackfromteacher', 'assignment', $this->course->teacher));
253 echo '<table cellspacing="0" class="feedback">';
255 echo '<tr>';
256 echo '<td class="left picture">';
257 print_user_picture($teacher->id, $this->course->id, $teacher->picture);
258 echo '</td>';
259 echo '<td class="topic">';
260 echo '<div class="from">';
261 echo '<div class="fullname">'.fullname($teacher).'</div>';
262 echo '<div class="time">'.userdate($submission->timemarked).'</div>';
263 echo '</div>';
264 echo '</td>';
265 echo '</tr>';
267 echo '<tr>';
268 echo '<td class="left side">&nbsp;</td>';
269 echo '<td class="content">';
270 if ($this->assignment->grade) {
271 echo '<div class="grade">';
272 echo get_string("grade").': '.$this->display_grade($submission->grade);
273 echo '</div>';
274 echo '<div class="clearer"></div>';
277 echo '<div class="comment">';
278 echo format_text($submission->submissioncomment, $submission->format);
279 echo '</div>';
280 echo '</tr>';
282 echo '</table>';
286 * Returns a link with info about the state of the assignment submissions
288 * This is used by view_header to put this link at the top right of the page.
289 * For teachers it gives the number of submitted assignments with a link
290 * For students it gives the time of their submission.
291 * This will be suitable for most assignment types.
292 * @return string
294 function submittedlink() {
295 global $USER;
297 $submitted = '';
299 $context = get_context_instance(CONTEXT_MODULE,$this->cm->id);
300 if (has_capability('mod/assignment:grade', $context)) {
302 // if this user can mark and is put in a group
303 // then he can only see/mark submission in his own groups
304 if (!has_capability('moodle/course:managegroups', $context) and (groups_get_activity_groupmode($this->cm) == SEPARATEGROUPS)) {
305 $count = $this->count_real_submissions($this->currentgroup); // Only their groups
306 } else {
307 $count = $this->count_real_submissions(); // Everyone
309 $submitted = '<a href="submissions.php?id='.$this->cm->id.'">'.
310 get_string('viewsubmissions', 'assignment', $count).'</a>';
311 } else {
312 if (!empty($USER->id)) {
313 if ($submission = $this->get_submission($USER->id)) {
314 if ($submission->timemodified) {
315 if ($submission->timemodified <= $this->assignment->timedue || empty($this->assignment->timedue)) {
316 $submitted = '<span class="early">'.userdate($submission->timemodified).'</span>';
317 } else {
318 $submitted = '<span class="late">'.userdate($submission->timemodified).'</span>';
325 return $submitted;
329 function setup_elements(&$mform) {
334 * Create a new assignment activity
336 * Given an object containing all the necessary data,
337 * (defined by the form in mod.html) this function
338 * will create a new instance and return the id number
339 * of the new instance.
340 * The due data is added to the calendar
341 * This is common to all assignment types.
343 * @param $assignment object The data from the form on mod.html
344 * @return int The id of the assignment
346 function add_instance($assignment) {
347 global $COURSE;
349 $assignment->timemodified = time();
350 $assignment->courseid = $assignment->course;
352 if ($returnid = insert_record("assignment", $assignment)) {
353 $assignment->id = $returnid;
355 if ($assignment->timedue) {
356 $event = new object();
357 $event->name = $assignment->name;
358 $event->description = $assignment->description;
359 $event->courseid = $assignment->course;
360 $event->groupid = 0;
361 $event->userid = 0;
362 $event->modulename = 'assignment';
363 $event->instance = $returnid;
364 $event->eventtype = 'due';
365 $event->timestart = $assignment->timedue;
366 $event->timeduration = 0;
368 add_event($event);
371 $assignment = stripslashes_recursive($assignment);
372 assignment_grade_item_update($assignment);
377 return $returnid;
381 * Deletes an assignment activity
383 * Deletes all database records, files and calendar events for this assignment.
384 * @param $assignment object The assignment to be deleted
385 * @return boolean False indicates error
387 function delete_instance($assignment) {
388 global $CFG;
390 $assignment->courseid = $assignment->course;
392 $result = true;
394 if (! delete_records('assignment_submissions', 'assignment', $assignment->id)) {
395 $result = false;
398 if (! delete_records('assignment', 'id', $assignment->id)) {
399 $result = false;
402 if (! delete_records('event', 'modulename', 'assignment', 'instance', $assignment->id)) {
403 $result = false;
406 // delete file area with all attachments - ignore errors
407 require_once($CFG->libdir.'/filelib.php');
408 fulldelete($CFG->dataroot.'/'.$assignment->course.'/'.$CFG->moddata.'/assignment/'.$assignment->id);
410 assignment_grade_item_delete($assignment);
412 return $result;
416 * Updates a new assignment activity
418 * Given an object containing all the necessary data,
419 * (defined by the form in mod.html) this function
420 * will update the assignment instance and return the id number
421 * The due date is updated in the calendar
422 * This is common to all assignment types.
424 * @param $assignment object The data from the form on mod.html
425 * @return int The assignment id
427 function update_instance($assignment) {
428 global $COURSE;
430 $assignment->timemodified = time();
432 $assignment->id = $assignment->instance;
433 $assignment->courseid = $assignment->course;
435 if (!update_record('assignment', $assignment)) {
436 return false;
439 if ($assignment->timedue) {
440 $event = new object();
442 if ($event->id = get_field('event', 'id', 'modulename', 'assignment', 'instance', $assignment->id)) {
444 $event->name = $assignment->name;
445 $event->description = $assignment->description;
446 $event->timestart = $assignment->timedue;
448 update_event($event);
449 } else {
450 $event = new object();
451 $event->name = $assignment->name;
452 $event->description = $assignment->description;
453 $event->courseid = $assignment->course;
454 $event->groupid = 0;
455 $event->userid = 0;
456 $event->modulename = 'assignment';
457 $event->instance = $assignment->id;
458 $event->eventtype = 'due';
459 $event->timestart = $assignment->timedue;
460 $event->timeduration = 0;
462 add_event($event);
464 } else {
465 delete_records('event', 'modulename', 'assignment', 'instance', $assignment->id);
468 // get existing grade item
469 $assignment = stripslashes_recursive($assignment);
471 assignment_grade_item_update($assignment);
473 return true;
477 * Update grade item for this submission.
479 function update_grade($submission) {
480 assignment_update_grades($this->assignment, $submission->userid);
484 * Top-level function for handling of submissions called by submissions.php
486 * This is for handling the teacher interaction with the grading interface
487 * This should be suitable for most assignment types.
489 * @param $mode string Specifies the kind of teacher interaction taking place
491 function submissions($mode) {
492 ///The main switch is changed to facilitate
493 ///1) Batch fast grading
494 ///2) Skip to the next one on the popup
495 ///3) Save and Skip to the next one on the popup
497 //make user global so we can use the id
498 global $USER;
500 // no grading when grades are locked
501 if ($this->lockedgrades) {
502 $mode = 'all';
505 switch ($mode) {
506 case 'grade': // We are in a popup window grading
507 if ($submission = $this->process_feedback()) {
508 //IE needs proper header with encoding
509 print_header(get_string('feedback', 'assignment').':'.format_string($this->assignment->name));
510 print_heading(get_string('changessaved'));
511 print $this->update_main_listing($submission);
513 close_window();
514 break;
516 case 'single': // We are in a popup window displaying submission
517 $this->display_submission();
518 break;
520 case 'all': // Main window, display everything
521 $this->display_submissions();
522 break;
524 case 'fastgrade':
525 ///do the fast grading stuff - this process should work for all 3 subclasses
526 $grading = false;
527 $commenting = false;
528 $col = false;
529 if (isset($_POST['submissioncomment'])) {
530 $col = 'submissioncomment';
531 $commenting = true;
533 if (isset($_POST['menu'])) {
534 $col = 'menu';
535 $grading = true;
537 if (!$col) {
538 //both submissioncomment and grade columns collapsed..
539 $this->display_submissions();
540 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 $submission->mailed = $updatedb?0:$submission->mailed;//only change if it's an update
579 $submission->timemarked = time();
581 //if it is not an update, we don't change the last modified time etc.
582 //this will also not write into database if no submissioncomment and grade is entered.
584 if ($updatedb){
585 if ($newsubmission) {
586 if (!$sid = insert_record('assignment_submissions', $submission)) {
587 return false;
589 $submission->id = $sid;
590 } else {
591 if (!update_record('assignment_submissions', $submission)) {
592 return false;
596 // triger grade event
597 $this->update_grade($submission);
599 //add to log only if updating
600 add_to_log($this->course->id, 'assignment', 'update grades',
601 'submissions.php?id='.$this->assignment->id.'&user='.$submission->userid,
602 $submission->userid, $this->cm->id);
607 $message = notify(get_string('changessaved'), 'notifysuccess', 'center', true);
609 $this->display_submissions($message);
610 break;
613 case 'next':
614 /// We are currently in pop up, but we want to skip to next one without saving.
615 /// This turns out to be similar to a single case
616 /// The URL used is for the next submission.
618 $this->display_submission();
619 break;
621 case 'saveandnext':
622 ///We are in pop up. save the current one and go to the next one.
623 //first we save the current changes
624 if ($submission = $this->process_feedback()) {
625 //print_heading(get_string('changessaved'));
626 $extra_javascript = $this->update_main_listing($submission);
629 //then we display the next submission
630 $this->display_submission($extra_javascript);
631 break;
633 default:
634 echo "something seriously is wrong!!";
635 break;
640 * Helper method updating the listing on the main script from popup using javascript
642 * @param $submission object The submission whose data is to be updated on the main page
644 function update_main_listing($submission) {
645 global $SESSION, $CFG;
647 $output = '';
649 $perpage = get_user_preferences('assignment_perpage', 10);
651 $quickgrade = get_user_preferences('assignment_quickgrade', 0);
653 /// Run some Javascript to try and update the parent page
654 $output .= '<script type="text/javascript">'."\n<!--\n";
655 if (empty($SESSION->flextable['mod-assignment-submissions']->collapse['submissioncomment'])) {
656 if ($quickgrade){
657 $output.= 'opener.document.getElementById("submissioncomment'.$submission->userid.'").value="'
658 .trim($submission->submissioncomment).'";'."\n";
659 } else {
660 $output.= 'opener.document.getElementById("com'.$submission->userid.
661 '").innerHTML="'.shorten_text(trim(strip_tags($submission->submissioncomment)), 15)."\";\n";
665 if (empty($SESSION->flextable['mod-assignment-submissions']->collapse['grade'])) {
666 //echo optional_param('menuindex');
667 if ($quickgrade){
668 $output.= 'opener.document.getElementById("menumenu'.$submission->userid.
669 '").selectedIndex="'.optional_param('menuindex', 0, PARAM_INT).'";'."\n";
670 } else {
671 $output.= 'opener.document.getElementById("g'.$submission->userid.'").innerHTML="'.
672 $this->display_grade($submission->grade)."\";\n";
675 //need to add student's assignments in there too.
676 if (empty($SESSION->flextable['mod-assignment-submissions']->collapse['timemodified']) &&
677 $submission->timemodified) {
678 $output.= 'opener.document.getElementById("ts'.$submission->userid.
679 '").innerHTML="'.addslashes_js($this->print_student_answer($submission->userid)).userdate($submission->timemodified)."\";\n";
682 if (empty($SESSION->flextable['mod-assignment-submissions']->collapse['timemarked']) &&
683 $submission->timemarked) {
684 $output.= 'opener.document.getElementById("tt'.$submission->userid.
685 '").innerHTML="'.userdate($submission->timemarked)."\";\n";
688 if (empty($SESSION->flextable['mod-assignment-submissions']->collapse['status'])) {
689 $output.= 'opener.document.getElementById("up'.$submission->userid.'").className="s1";';
690 $buttontext = get_string('update');
691 $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),
692 'grade'.$submission->userid, $buttontext, 450, 700, $buttontext, 'none', true, 'button'.$submission->userid);
693 $output.= 'opener.document.getElementById("up'.$submission->userid.'").innerHTML="'.addslashes_js($button).'";';
696 if (!empty($CFG->enableoutcomes) and empty($SESSION->flextable['mod-assignment-submissions']->collapse['outcomes'])) {
697 if ($outcomes_data = grade_get_outcomes($this->course->id, 'mod', 'assignment', $this->assignment->id, $submission->userid)) {
698 foreach($outcomes_data as $n=>$data) {
699 if ($data->locked) {
700 continue;
703 if ($quickgrade){
704 $output.= 'opener.document.getElementById("outcome_'.$n.'_'.$submission->userid.
705 '").selectedIndex="'.$data->grade.'";'."\n";
706 } else {
707 $options = make_grades_menu(-$data->scaleid);
708 $options[0] = get_string('nooutcome', 'grades');
709 $output.= 'opener.document.getElementById("outcome_'.$n.'_'.$submission->userid.'").innerHTML="'.$options[$data->grade]."\";\n";
717 $output .= "\n-->\n</script>";
718 return $output;
722 * Return a grade in user-friendly form, whether it's a scale or not
724 * @param $grade
725 * @return string User-friendly representation of grade
727 function display_grade($grade) {
729 static $scalegrades = array(); // Cache scales for each assignment - they might have different scales!!
731 if ($this->assignment->grade >= 0) { // Normal number
732 if ($grade == -1) {
733 return '-';
734 } else {
735 return $grade.' / '.$this->assignment->grade;
738 } else { // Scale
739 if (empty($scalegrades[$this->assignment->id])) {
740 if ($scale = get_record('scale', 'id', -($this->assignment->grade))) {
741 $scalegrades[$this->assignment->id] = make_menu_from_list($scale->scale);
742 } else {
743 return '-';
746 if (isset($scalegrades[$this->assignment->id][$grade])) {
747 return $scalegrades[$this->assignment->id][$grade];
749 return '-';
754 * Display a single submission, ready for grading on a popup window
756 * This default method prints the teacher info and submissioncomment box at the top and
757 * the student info and submission at the bottom.
758 * This method also fetches the necessary data in order to be able to
759 * provide a "Next submission" button.
760 * Calls preprocess_submission() to give assignment type plug-ins a chance
761 * to process submissions before they are graded
762 * This method gets its arguments from the page parameters userid and offset
764 function display_submission($extra_javascript = '') {
766 global $CFG;
767 require_once($CFG->libdir.'/gradelib.php');
769 $userid = required_param('userid', PARAM_INT);
770 $offset = required_param('offset', PARAM_INT);//offset for where to start looking for student.
772 if (!$user = get_record('user', 'id', $userid)) {
773 error('No such user!');
776 if (!$submission = $this->get_submission($user->id)) {
777 $submission = $this->prepare_new_submission($userid);
779 if ($submission->timemodified > $submission->timemarked) {
780 $subtype = 'assignmentnew';
781 } else {
782 $subtype = 'assignmentold';
785 /// construct SQL, using current offset to find the data of the next student
786 $course = $this->course;
787 $assignment = $this->assignment;
788 $cm = $this->cm;
789 $context = get_context_instance(CONTEXT_MODULE, $cm->id);
791 /// Get all ppl that can submit assignments
793 $currentgroup = groups_get_activity_group($cm);
795 $users = get_users_by_capability($context, 'mod/assignment:submit', 'u.id, u.id', '', '', '', $currentgroup, '', false);
797 $select = 'SELECT u.id, u.firstname, u.lastname, u.picture,
798 s.id AS submissionid, s.grade, s.submissioncomment,
799 s.timemodified, s.timemarked ';
800 $sql = 'FROM '.$CFG->prefix.'user u '.
801 'LEFT JOIN '.$CFG->prefix.'assignment_submissions s ON u.id = s.userid
802 AND s.assignment = '.$this->assignment->id.' '.
803 'WHERE u.id IN ('.implode(',', array_keys($users)).') ';
805 require_once($CFG->libdir.'/tablelib.php');
807 if ($sort = flexible_table::get_sql_sort('mod-assignment-submissions')) {
808 $sort = 'ORDER BY '.$sort.' ';
811 $nextid = 0;
812 if (($auser = get_records_sql($select.$sql.$sort, $offset+1, 1)) !== false) {
813 $nextuser = array_shift($auser);
814 /// Calculate user status
815 $nextuser->status = ($nextuser->timemarked > 0) && ($nextuser->timemarked >= $nextuser->timemodified);
816 $nextid = $nextuser->id;
819 print_header(get_string('feedback', 'assignment').':'.fullname($user, true).':'.format_string($this->assignment->name));
821 /// Print any extra javascript needed for saveandnext
822 echo $extra_javascript;
824 ///SOme javascript to help with setting up >.>
826 echo '<script type="text/javascript">'."\n";
827 echo 'function setNext(){'."\n";
828 echo 'document.getElementById(\'submitform\').mode.value=\'next\';'."\n";
829 echo 'document.getElementById(\'submitform\').userid.value="'.$nextid.'";'."\n";
830 echo '}'."\n";
832 echo 'function saveNext(){'."\n";
833 echo 'document.getElementById(\'submitform\').mode.value=\'saveandnext\';'."\n";
834 echo 'document.getElementById(\'submitform\').userid.value="'.$nextid.'";'."\n";
835 echo 'document.getElementById(\'submitform\').saveuserid.value="'.$userid.'";'."\n";
836 echo 'document.getElementById(\'submitform\').menuindex.value = document.getElementById(\'submitform\').grade.selectedIndex;'."\n";
837 echo '}'."\n";
839 echo '</script>'."\n";
840 echo '<table cellspacing="0" class="feedback '.$subtype.'" >';
842 ///Start of teacher info row
844 echo '<tr>';
845 echo '<td class="picture teacher">';
846 if ($submission->teacher) {
847 $teacher = get_record('user', 'id', $submission->teacher);
848 } else {
849 global $USER;
850 $teacher = $USER;
852 print_user_picture($teacher->id, $this->course->id, $teacher->picture);
853 echo '</td>';
854 echo '<td class="content">';
855 echo '<form id="submitform" action="submissions.php" method="post">';
856 echo '<div>'; // xhtml compatibility - invisiblefieldset was breaking layout here
857 echo '<input type="hidden" name="offset" value="'.($offset+1).'" />';
858 echo '<input type="hidden" name="userid" value="'.$userid.'" />';
859 echo '<input type="hidden" name="id" value="'.$this->cm->id.'" />';
860 echo '<input type="hidden" name="mode" value="grade" />';
861 echo '<input type="hidden" name="menuindex" value="0" />';//selected menu index
863 //new hidden field, initialized to -1.
864 echo '<input type="hidden" name="saveuserid" value="-1" />';
866 if ($submission->timemarked) {
867 echo '<div class="from">';
868 echo '<div class="fullname">'.fullname($teacher, true).'</div>';
869 echo '<div class="time">'.userdate($submission->timemarked).'</div>';
870 echo '</div>';
872 echo '<div class="grade"><label for="menugrade">'.get_string('grade').'</label> ';
873 choose_from_menu(make_grades_menu($this->assignment->grade), 'grade', $submission->grade, get_string('nograde'), '', -1);
874 echo '</div>';
876 echo '<div class="clearer"></div>';
878 if (!empty($CFG->enableoutcomes) and $outcomes_data = grade_get_outcomes($this->course->id, 'mod', 'assignment', $this->assignment->id, $userid)) {
879 foreach($outcomes_data as $n=>$data) {
880 echo '<div class="outcome"><label for="menuoutcome_'.$n.'">'.format_string($data->name).'</label> ';
881 $options = make_grades_menu(-$data->scaleid);
882 if ($data->locked) {
883 $options[0] = get_string('nooutcome', 'grades');
884 echo $options[$data->grade];
885 } else {
886 choose_from_menu($options, 'outcome_'.$n.'['.$userid.']', $data->grade, get_string('nooutcome', 'grades'), '', 0, false, false, 0, 'menuoutcome_'.$n);
888 echo '</div>';
889 echo '<div class="clearer"></div>';
894 $this->preprocess_submission($submission);
896 print_textarea($this->usehtmleditor, 14, 58, 0, 0, 'submissioncomment', $submission->submissioncomment, $this->course->id);
898 if ($this->usehtmleditor) {
899 echo '<input type="hidden" name="format" value="'.FORMAT_HTML.'" />';
900 } else {
901 echo '<div class="format">';
902 choose_from_menu(format_text_menu(), "format", $submission->format, "");
903 helpbutton("textformat", get_string("helpformatting"));
904 echo '</div>';
907 ///Print Buttons in Single View
908 echo '<div class="buttons">';
909 echo '<input type="submit" name="submit" value="'.get_string('savechanges').'" onclick = "document.getElementById(\'submitform\').menuindex.value = document.getElementById(\'submitform\').grade.selectedIndex" />';
910 echo '<input type="submit" name="cancel" value="'.get_string('cancel').'" />';
911 //if there are more to be graded.
912 if ($nextid) {
913 echo '<input type="submit" name="saveandnext" value="'.get_string('saveandnext').'" onclick="saveNext()" />';
914 echo '<input type="submit" name="next" value="'.get_string('next').'" onclick="setNext();" />';
916 echo '</div>';
917 echo '</div></form>';
919 $customfeedback = $this->custom_feedbackform($submission, true);
920 if (!empty($customfeedback)) {
921 echo $customfeedback;
924 echo '</td></tr>';
926 ///End of teacher info row, Start of student info row
927 echo '<tr>';
928 echo '<td class="picture user">';
929 print_user_picture($user->id, $this->course->id, $user->picture);
930 echo '</td>';
931 echo '<td class="topic">';
932 echo '<div class="from">';
933 echo '<div class="fullname">'.fullname($user, true).'</div>';
934 if ($submission->timemodified) {
935 echo '<div class="time">'.userdate($submission->timemodified).
936 $this->display_lateness($submission->timemodified).'</div>';
938 echo '</div>';
939 $this->print_user_files($user->id);
940 echo '</td>';
941 echo '</tr>';
943 ///End of student info row
945 echo '</table>';
947 if ($this->usehtmleditor) {
948 use_html_editor();
951 print_footer('none');
955 * Preprocess submission before grading
957 * Called by display_submission()
958 * The default type does nothing here.
959 * @param $submission object The submission object
961 function preprocess_submission(&$submission) {
965 * Display all the submissions ready for grading
967 function display_submissions($message='') {
968 global $CFG, $db, $USER;
969 require_once($CFG->libdir.'/gradelib.php');
971 /* first we check to see if the form has just been submitted
972 * to request user_preference updates
975 if (isset($_POST['updatepref'])){
976 $perpage = optional_param('perpage', 10, PARAM_INT);
977 $perpage = ($perpage <= 0) ? 10 : $perpage ;
978 set_user_preference('assignment_perpage', $perpage);
979 set_user_preference('assignment_quickgrade', optional_param('quickgrade',0, PARAM_BOOL));
982 /* next we get perpage and quickgrade (allow quick grade) params
983 * from database
985 $perpage = get_user_preferences('assignment_perpage', 10);
987 if ($this->lockedgrades) {
988 $quickgrade = 0;
989 } else {
990 $quickgrade = get_user_preferences('assignment_quickgrade', 0);
993 if (!empty($CFG->enableoutcomes) and grade_get_outcomes($this->course->id, 'mod', 'assignment', $this->assignment->id)) {
994 $uses_outcomes = true;
995 } else {
996 $uses_outcomes = false;
999 $teacherattempts = true; /// Temporary measure
1000 $page = optional_param('page', 0, PARAM_INT);
1001 $strsaveallfeedback = get_string('saveallfeedback', 'assignment');
1003 /// Some shortcuts to make the code read better
1005 $course = $this->course;
1006 $assignment = $this->assignment;
1007 $cm = $this->cm;
1009 $tabindex = 1; //tabindex for quick grading tabbing; Not working for dropdowns yet
1011 add_to_log($course->id, 'assignment', 'view submission', 'submissions.php?id='.$this->assignment->id, $this->assignment->id, $this->cm->id);
1013 $navlinks = array();
1014 $navlinks[] = array('name' => $this->strassignments, 'link' => "index.php?id=$course->id", 'type' => 'activity');
1015 $navlinks[] = array('name' => format_string($this->assignment->name,true),
1016 'link' => "view.php?a={$this->assignment->id}",
1017 'type' => 'activityinstance');
1018 $navlinks[] = array('name' => $this->strsubmissions, 'link' => '', 'type' => 'title');
1019 $navigation = build_navigation($navlinks);
1021 print_header_simple(format_string($this->assignment->name,true), "", $navigation,
1022 '', '', true, update_module_button($cm->id, $course->id, $this->strassignment), navmenu($course, $cm));
1024 if (!empty($message)) {
1025 echo $message; // display messages here if any
1028 $context = get_context_instance(CONTEXT_MODULE, $cm->id);
1030 /// find out current groups mode
1031 $groupmode = groups_get_activity_groupmode($cm);
1032 $currentgroup = groups_get_activity_group($cm, true);
1033 groups_print_activity_menu($cm, 'submissions.php?id=' . $this->cm->id);
1035 /// Get all ppl that are allowed to submit assignments
1036 $users = get_users_by_capability($context, 'mod/assignment:submit', '', '', '', '', $currentgroup, '', false);
1037 $users = array_keys($users);
1039 if (!empty($CFG->enablegroupings) && !empty($cm->groupingid)) {
1040 $groupingusers = groups_get_grouping_members($cm->groupingid, 'u.id', 'u.id');
1041 $users = array_intersect($users, array_keys($groupingusers));
1045 $tablecolumns = array('picture', 'fullname', 'grade', 'submissioncomment', 'timemodified', 'timemarked', 'status');
1046 if ($uses_outcomes) {
1047 $tablecolumns[] = ''; // no sorting based on outcomes column
1050 $tableheaders = array('',
1051 get_string('fullname'),
1052 get_string('grade'),
1053 get_string('comment', 'assignment'),
1054 get_string('lastmodified').' ('.$course->student.')',
1055 get_string('lastmodified').' ('.$course->teacher.')',
1056 get_string('status'));
1057 if ($uses_outcomes) {
1058 $tableheaders[] = get_string('outcomes', 'grades');
1061 require_once($CFG->libdir.'/tablelib.php');
1062 $table = new flexible_table('mod-assignment-submissions');
1064 $table->define_columns($tablecolumns);
1065 $table->define_headers($tableheaders);
1066 $table->define_baseurl($CFG->wwwroot.'/mod/assignment/submissions.php?id='.$this->cm->id.'&amp;currentgroup='.$currentgroup);
1068 $table->sortable(true, 'lastname');//sorted by lastname by default
1069 $table->collapsible(true);
1070 $table->initialbars(true);
1072 $table->column_suppress('picture');
1073 $table->column_suppress('fullname');
1075 $table->column_class('picture', 'picture');
1076 $table->column_class('fullname', 'fullname');
1077 $table->column_class('grade', 'grade');
1078 $table->column_class('submissioncomment', 'comment');
1079 $table->column_class('timemodified', 'timemodified');
1080 $table->column_class('timemarked', 'timemarked');
1081 $table->column_class('status', 'status');
1082 if ($uses_outcomes) {
1083 $table->column_class('outcomes', 'outcomes');
1086 $table->set_attribute('cellspacing', '0');
1087 $table->set_attribute('id', 'attempts');
1088 $table->set_attribute('class', 'submissions');
1089 $table->set_attribute('width', '90%');
1090 //$table->set_attribute('align', 'center');
1092 // Start working -- this is necessary as soon as the niceties are over
1093 $table->setup();
1095 /// Check to see if groups are being used in this assignment
1097 if (!$teacherattempts) {
1098 $teachers = get_course_teachers($course->id);
1099 if (!empty($teachers)) {
1100 $keys = array_keys($teachers);
1102 foreach ($keys as $key) {
1103 unset($users[$key]);
1107 if (empty($users)) {
1108 print_heading(get_string('noattempts','assignment'));
1109 return true;
1112 /// Construct the SQL
1114 if ($where = $table->get_sql_where()) {
1115 $where .= ' AND ';
1118 if ($sort = $table->get_sql_sort()) {
1119 $sort = ' ORDER BY '.$sort;
1122 $select = 'SELECT u.id, u.firstname, u.lastname, u.picture,
1123 s.id AS submissionid, s.grade, s.submissioncomment,
1124 s.timemodified, s.timemarked ';
1125 $sql = 'FROM '.$CFG->prefix.'user u '.
1126 'LEFT JOIN '.$CFG->prefix.'assignment_submissions s ON u.id = s.userid
1127 AND s.assignment = '.$this->assignment->id.' '.
1128 'WHERE '.$where.'u.id IN ('.implode(',',$users).') ';
1130 $table->pagesize($perpage, count($users));
1132 ///offset used to calculate index of student in that particular query, needed for the pop up to know who's next
1133 $offset = $page * $perpage;
1135 $strupdate = get_string('update');
1136 $strgrade = get_string('grade');
1137 $grademenu = make_grades_menu($this->assignment->grade);
1139 if (($ausers = get_records_sql($select.$sql.$sort, $table->get_page_start(), $table->get_page_size())) !== false) {
1141 foreach ($ausers as $auser) {
1142 /// Calculate user status
1143 $auser->status = ($auser->timemarked > 0) && ($auser->timemarked >= $auser->timemodified);
1144 $picture = print_user_picture($auser->id, $course->id, $auser->picture, false, true);
1146 if (empty($auser->submissionid)) {
1147 $auser->grade = -1; //no submission yet
1150 if (!empty($auser->submissionid)) {
1151 ///Prints student answer and student modified date
1152 ///attach file or print link to student answer, depending on the type of the assignment.
1153 ///Refer to print_student_answer in inherited classes.
1154 if ($auser->timemodified > 0) {
1155 $studentmodified = '<div id="ts'.$auser->id.'">'.$this->print_student_answer($auser->id)
1156 . userdate($auser->timemodified).'</div>';
1157 } else {
1158 $studentmodified = '<div id="ts'.$auser->id.'">&nbsp;</div>';
1160 ///Print grade, dropdown or text
1161 if ($auser->timemarked > 0) {
1162 $teachermodified = '<div id="tt'.$auser->id.'">'.userdate($auser->timemarked).'</div>';
1164 if ($quickgrade) {
1165 $menu = choose_from_menu(make_grades_menu($this->assignment->grade),
1166 'menu['.$auser->id.']', $auser->grade,
1167 get_string('nograde'),'',-1,true,false,$tabindex++);
1168 $grade = '<div id="g'.$auser->id.'">'. $menu .'</div>';
1169 } else {
1170 $grade = '<div id="g'.$auser->id.'">'.$this->display_grade($auser->grade).'</div>';
1173 } else {
1174 $teachermodified = '<div id="tt'.$auser->id.'">&nbsp;</div>';
1175 if ($quickgrade) {
1176 $menu = choose_from_menu(make_grades_menu($this->assignment->grade),
1177 'menu['.$auser->id.']', $auser->grade,
1178 get_string('nograde'),'',-1,true,false,$tabindex++);
1179 $grade = '<div id="g'.$auser->id.'">'.$menu.'</div>';
1180 } else {
1181 $grade = '<div id="g'.$auser->id.'">'.$this->display_grade($auser->grade).'</div>';
1184 ///Print Comment
1185 if ($quickgrade) {
1186 $comment = '<div id="com'.$auser->id.'">'
1187 . '<textarea tabindex="'.$tabindex++.'" name="submissioncomment['.$auser->id.']" id="submissioncomment'
1188 . $auser->id.'" rows="2" cols="20">'.($auser->submissioncomment).'</textarea></div>';
1189 } else {
1190 $comment = '<div id="com'.$auser->id.'">'.shorten_text(strip_tags($auser->submissioncomment),15).'</div>';
1192 } else {
1193 $studentmodified = '<div id="ts'.$auser->id.'">&nbsp;</div>';
1194 $teachermodified = '<div id="tt'.$auser->id.'">&nbsp;</div>';
1195 $status = '<div id="st'.$auser->id.'">&nbsp;</div>';
1197 if ($quickgrade) { // allow editing
1198 $menu = choose_from_menu(make_grades_menu($this->assignment->grade),
1199 'menu['.$auser->id.']', $auser->grade,
1200 get_string('nograde'),'',-1,true,false,$tabindex++);
1201 $grade = '<div id="g'.$auser->id.'">'.$menu.'</div>';
1202 } else {
1203 $grade = '<div id="g'.$auser->id.'">-</div>';
1206 if ($quickgrade) {
1207 $comment = '<div id="com'.$auser->id.'">'
1208 . '<textarea tabindex="'.$tabindex++.'" name="submissioncomment['.$auser->id.']" id="submissioncomment'
1209 . $auser->id.'" rows="2" cols="20">'.($auser->submissioncomment).'</textarea></div>';
1210 } else {
1211 $comment = '<div id="com'.$auser->id.'">&nbsp;</div>';
1215 if (empty($auser->status)) { /// Confirm we have exclusively 0 or 1
1216 $auser->status = 0;
1217 } else {
1218 $auser->status = 1;
1221 $buttontext = ($auser->status == 1) ? $strupdate : $strgrade;
1223 if ($this->lockedgrades) {
1224 $status = get_string('gradeitemlocked', 'grades');
1225 } else {
1226 ///No more buttons, we use popups ;-).
1227 $popup_url = '/mod/assignment/submissions.php?id='.$this->cm->id
1228 . '&amp;userid='.$auser->id.'&amp;mode=single'.'&amp;offset='.$offset++;
1229 $button = link_to_popup_window ($popup_url, 'grade'.$auser->id, $buttontext, 600, 780,
1230 $buttontext, 'none', true, 'button'.$auser->id);
1232 $status = '<div id="up'.$auser->id.'" class="s'.$auser->status.'">'.$button.'</div>';
1235 $outcomes = '';
1237 if ($uses_outcomes and $outcomes_data = grade_get_outcomes($this->course->id, 'mod', 'assignment', $this->assignment->id, $auser->id)) {
1239 foreach($outcomes_data as $n=>$data) {
1240 $outcomes .= '<div class="outcome"><label>'.format_string($data->name).'</label>';
1241 $options = make_grades_menu(-$data->scaleid);
1243 if ($data->locked or !$quickgrade) {
1244 $options[0] = get_string('nooutcome', 'grades');
1245 $outcomes .= ': <span id="outcome_'.$n.'_'.$auser->id.'">'.$options[$data->grade].'</span>';
1246 } else {
1247 $outcomes .= ' ';
1248 $outcomes .= choose_from_menu($options, 'outcome_'.$n.'['.$auser->id.']',
1249 $data->grade, get_string('nooutcome', 'grades'), '', 0, true, false, 0, 'outcome_'.$n.'_'.$auser->id);
1251 $outcomes .= '</div>';
1256 $row = array($picture, fullname($auser), $grade, $comment, $studentmodified, $teachermodified, $status);
1257 if ($uses_outcomes) {
1258 $row[] = $outcomes;
1261 $table->add_data($row);
1265 /// Print quickgrade form around the table
1266 if ($quickgrade){
1267 echo '<form action="submissions.php" id="fastg" method="post">';
1268 echo '<div>';
1269 echo '<input type="hidden" name="id" value="'.$this->cm->id.'" />';
1270 echo '<input type="hidden" name="mode" value="fastgrade" />';
1271 echo '<input type="hidden" name="page" value="'.$page.'" />';
1272 echo '</div>';
1273 //echo '<div style="text-align:center"><input type="submit" name="fastg" value="'.get_string('saveallfeedback', 'assignment').'" /></div>';
1276 $table->print_html(); /// Print the whole table
1278 if ($quickgrade){
1279 echo '<div style="text-align:center"><input type="submit" name="fastg" value="'.get_string('saveallfeedback', 'assignment').'" /></div>';
1280 echo '</form>';
1282 /// End of fast grading form
1284 /// Mini form for setting user preference
1285 echo '<br />';
1286 echo '<form id="options" action="submissions.php?id='.$this->cm->id.'" method="post">';
1287 echo '<fieldset class="invisiblefieldset">';
1288 echo '<input type="hidden" id="updatepref" name="updatepref" value="1" />';
1289 echo '<table id="optiontable">';
1290 echo '<tr align="right"><td>';
1291 echo '<label for="perpage">'.get_string('pagesize','assignment').'</label>';
1292 echo ':</td>';
1293 echo '<td align="left">';
1294 echo '<input type="text" id="perpage" name="perpage" size="1" value="'.$perpage.'" />';
1295 helpbutton('pagesize', get_string('pagesize','assignment'), 'assignment');
1296 echo '</td></tr>';
1297 if (!$this->lockedgrades) {
1298 echo '<tr align="right">';
1299 echo '<td>';
1300 print_string('quickgrade','assignment');
1301 echo ':</td>';
1302 echo '<td align="left">';
1303 if ($quickgrade){
1304 echo '<input type="checkbox" name="quickgrade" value="1" checked="checked" />';
1305 } else {
1306 echo '<input type="checkbox" name="quickgrade" value="1" />';
1308 helpbutton('quickgrade', get_string('quickgrade', 'assignment'), 'assignment').'</p></div>';
1309 echo '</td></tr>';
1311 echo '<tr>';
1312 echo '<td colspan="2" align="right">';
1313 echo '<input type="submit" value="'.get_string('savepreferences').'" />';
1314 echo '</td></tr></table>';
1315 echo '</fieldset>';
1316 echo '</form>';
1317 ///End of mini form
1318 print_footer($this->course);
1322 * Process teacher feedback submission
1324 * This is called by submissions() when a grading even has taken place.
1325 * It gets its data from the submitted form.
1326 * @return object The updated submission object
1328 function process_feedback() {
1330 global $USER;
1332 if (!$feedback = data_submitted()) { // No incoming data?
1333 return false;
1336 ///For save and next, we need to know the userid to save, and the userid to go
1337 ///We use a new hidden field in the form, and set it to -1. If it's set, we use this
1338 ///as the userid to store
1339 if ((int)$feedback->saveuserid !== -1){
1340 $feedback->userid = $feedback->saveuserid;
1343 if (!empty($feedback->cancel)) { // User hit cancel button
1344 return false;
1347 // store outcomes if needed
1348 $this->process_outcomes($feedback->userid);
1350 $submission = $this->get_submission($feedback->userid, true); // Get or make one
1352 $submission->grade = $feedback->grade;
1353 $submission->submissioncomment = $feedback->submissioncomment;
1354 $submission->format = $feedback->format;
1355 $submission->teacher = $USER->id;
1356 $submission->mailed = 0; // Make sure mail goes out (again, even)
1357 $submission->timemarked = time();
1359 unset($submission->data1); // Don't need to update this.
1360 unset($submission->data2); // Don't need to update this.
1362 if (empty($submission->timemodified)) { // eg for offline assignments
1363 // $submission->timemodified = time();
1366 if (! update_record('assignment_submissions', $submission)) {
1367 return false;
1370 // triger grade event
1371 $this->update_grade($submission);
1373 add_to_log($this->course->id, 'assignment', 'update grades',
1374 'submissions.php?id='.$this->assignment->id.'&user='.$feedback->userid, $feedback->userid, $this->cm->id);
1376 return $submission;
1380 function process_outcomes($userid) {
1381 global $CFG, $USER;
1383 if (empty($CFG->enableoutcomes)) {
1384 return;
1387 require_once($CFG->libdir.'/gradelib.php');
1389 if (!$formdata = data_submitted()) {
1390 return;
1393 $data = array();
1394 if ($outcomes = grade_get_outcomes($this->course->id, 'mod', 'assignment', $this->assignment->id, $userid)) {
1395 foreach($outcomes as $n=>$old) {
1396 $name = 'outcome_'.$n;
1397 if (isset($formdata->{$name}[$userid]) and $old->grade != $formdata->{$name}[$userid]) {
1398 $data[$n] = $formdata->{$name}[$userid];
1402 if (count($data) > 0) {
1403 grade_update_outcomes('mod/assignment', $this->course->id, 'mod', 'assignment', $this->assignment->id, $userid, $data);
1409 * Load the submission object for a particular user
1411 * @param $userid int The id of the user whose submission we want or 0 in which case USER->id is used
1412 * @param $createnew boolean optional Defaults to false. If set to true a new submission object will be created in the database
1413 * @return object The submission
1415 function get_submission($userid=0, $createnew=false) {
1416 global $USER;
1418 if (empty($userid)) {
1419 $userid = $USER->id;
1422 $submission = get_record('assignment_submissions', 'assignment', $this->assignment->id, 'userid', $userid);
1424 if ($submission || !$createnew) {
1425 return $submission;
1427 $newsubmission = $this->prepare_new_submission($userid);
1428 if (!insert_record("assignment_submissions", $newsubmission)) {
1429 error("Could not insert a new empty submission");
1432 return get_record('assignment_submissions', 'assignment', $this->assignment->id, 'userid', $userid);
1436 * Instantiates a new submission object for a given user
1438 * Sets the assignment, userid and times, everything else is set to default values.
1439 * @param $userid int The userid for which we want a submission object
1440 * @return object The submission
1442 function prepare_new_submission($userid) {
1443 $submission = new Object;
1444 $submission->assignment = $this->assignment->id;
1445 $submission->userid = $userid;
1446 //$submission->timecreated = time();
1447 $submission->timecreated = '';
1448 // teachers should not be modifying modified date, except offline assignments
1449 $submission->timemodified = $submission->timecreated;
1450 $submission->numfiles = 0;
1451 $submission->data1 = '';
1452 $submission->data2 = '';
1453 $submission->grade = -1;
1454 $submission->submissioncomment = '';
1455 $submission->format = 0;
1456 $submission->teacher = 0;
1457 $submission->timemarked = 0;
1458 $submission->mailed = 0;
1459 return $submission;
1463 * Return all assignment submissions by ENROLLED students (even empty)
1465 * @param $sort string optional field names for the ORDER BY in the sql query
1466 * @param $dir string optional specifying the sort direction, defaults to DESC
1467 * @return array The submission objects indexed by id
1469 function get_submissions($sort='', $dir='DESC') {
1470 return assignment_get_all_submissions($this->assignment, $sort, $dir);
1474 * Counts all real assignment submissions by ENROLLED students (not empty ones)
1476 * @param $groupid int optional If nonzero then count is restricted to this group
1477 * @return int The number of submissions
1479 function count_real_submissions($groupid=0) {
1480 return assignment_count_real_submissions($this->assignment, $groupid);
1484 * Alerts teachers by email of new or changed assignments that need grading
1486 * First checks whether the option to email teachers is set for this assignment.
1487 * Sends an email to ALL teachers in the course (or in the group if using separate groups).
1488 * Uses the methods email_teachers_text() and email_teachers_html() to construct the content.
1489 * @param $submission object The submission that has changed
1491 function email_teachers($submission) {
1492 global $CFG;
1494 if (empty($this->assignment->emailteachers)) { // No need to do anything
1495 return;
1498 $user = get_record('user', 'id', $submission->userid);
1500 if ($teachers = $this->get_graders($user)) {
1502 $strassignments = get_string('modulenameplural', 'assignment');
1503 $strassignment = get_string('modulename', 'assignment');
1504 $strsubmitted = get_string('submitted', 'assignment');
1506 foreach ($teachers as $teacher) {
1507 $info = new object();
1508 $info->username = fullname($user, true);
1509 $info->assignment = format_string($this->assignment->name,true);
1510 $info->url = $CFG->wwwroot.'/mod/assignment/submissions.php?id='.$this->cm->id;
1512 $postsubject = $strsubmitted.': '.$info->username.' -> '.$this->assignment->name;
1513 $posttext = $this->email_teachers_text($info);
1514 $posthtml = ($teacher->mailformat == 1) ? $this->email_teachers_html($info) : '';
1516 @email_to_user($teacher, $user, $postsubject, $posttext, $posthtml); // If it fails, oh well, too bad.
1522 * Returns a list of teachers that should be grading given submission
1524 function get_graders($user) {
1525 //potential graders
1526 $potgraders = get_users_by_capability($this->context, 'mod/assignment:grade', '', '', '', '', '', '', false, false);
1528 $graders = array();
1529 if (groups_get_activity_groupmode($this->cm) == SEPARATEGROUPS) { // Separate groups are being used
1530 if ($groups = groups_get_all_groups($this->course->id, $user->id)) { // Try to find all groups
1531 foreach ($groups as $group) {
1532 foreach ($potgraders as $t) {
1533 if ($t->id == $user->id) {
1534 continue; // do not send self
1536 if (groups_is_member($group->id, $t->id)) {
1537 $graders[$t->id] = $t;
1541 } else {
1542 // user not in group, try to find graders without group
1543 foreach ($potgraders as $t) {
1544 if ($t->id == $user->id) {
1545 continue; // do not send self
1547 if (!groups_get_all_groups($this->course->id, $t->id)) { //ugly hack
1548 $graders[$t->id] = $t;
1552 } else {
1553 foreach ($potgraders as $t) {
1554 if ($t->id == $user->id) {
1555 continue; // do not send self
1557 $graders[$t->id] = $t;
1560 return $graders;
1564 * Creates the text content for emails to teachers
1566 * @param $info object The info used by the 'emailteachermail' language string
1567 * @return string
1569 function email_teachers_text($info) {
1570 $posttext = format_string($this->course->shortname).' -> '.$this->strassignments.' -> '.
1571 format_string($this->assignment->name)."\n";
1572 $posttext .= '---------------------------------------------------------------------'."\n";
1573 $posttext .= get_string("emailteachermail", "assignment", $info)."\n";
1574 $posttext .= "\n---------------------------------------------------------------------\n";
1575 return $posttext;
1579 * Creates the html content for emails to teachers
1581 * @param $info object The info used by the 'emailteachermailhtml' language string
1582 * @return string
1584 function email_teachers_html($info) {
1585 global $CFG;
1586 $posthtml = '<p><font face="sans-serif">'.
1587 '<a href="'.$CFG->wwwroot.'/course/view.php?id='.$this->course->id.'">'.format_string($this->course->shortname).'</a> ->'.
1588 '<a href="'.$CFG->wwwroot.'/mod/assignment/index.php?id='.$this->course->id.'">'.$this->strassignments.'</a> ->'.
1589 '<a href="'.$CFG->wwwroot.'/mod/assignment/view.php?id='.$this->cm->id.'">'.format_string($this->assignment->name).'</a></font></p>';
1590 $posthtml .= '<hr /><font face="sans-serif">';
1591 $posthtml .= '<p>'.get_string('emailteachermailhtml', 'assignment', $info).'</p>';
1592 $posthtml .= '</font><hr />';
1593 return $posthtml;
1597 * Produces a list of links to the files uploaded by a user
1599 * @param $userid int optional id of the user. If 0 then $USER->id is used.
1600 * @param $return boolean optional defaults to false. If true the list is returned rather than printed
1601 * @return string optional
1603 function print_user_files($userid=0, $return=false) {
1604 global $CFG, $USER;
1606 if (!$userid) {
1607 if (!isloggedin()) {
1608 return '';
1610 $userid = $USER->id;
1613 $filearea = $this->file_area_name($userid);
1615 $output = '';
1617 if ($basedir = $this->file_area($userid)) {
1618 if ($files = get_directory_list($basedir)) {
1619 require_once($CFG->libdir.'/filelib.php');
1620 foreach ($files as $key => $file) {
1622 $icon = mimeinfo('icon', $file);
1624 if ($CFG->slasharguments) {
1625 $ffurl = "$CFG->wwwroot/file.php/$filearea/$file";
1626 } else {
1627 $ffurl = "$CFG->wwwroot/file.php?file=/$filearea/$file";
1630 $output .= '<img align="middle" src="'.$CFG->pixpath.'/f/'.$icon.'" class="icon" alt="'.$icon.'" />'.
1631 '<a href="'.$ffurl.'" >'.$file.'</a><br />';
1636 $output = '<div class="files">'.$output.'</div>';
1638 if ($return) {
1639 return $output;
1641 echo $output;
1645 * Count the files uploaded by a given user
1647 * @param $userid int The user id
1648 * @return int
1650 function count_user_files($userid) {
1651 global $CFG;
1653 $filearea = $this->file_area_name($userid);
1655 if ( is_dir($CFG->dataroot.'/'.$filearea) && $basedir = $this->file_area($userid)) {
1656 if ($files = get_directory_list($basedir)) {
1657 return count($files);
1660 return 0;
1664 * Creates a directory file name, suitable for make_upload_directory()
1666 * @param $userid int The user id
1667 * @return string path to file area
1669 function file_area_name($userid) {
1670 global $CFG;
1672 return $this->course->id.'/'.$CFG->moddata.'/assignment/'.$this->assignment->id.'/'.$userid;
1676 * Makes an upload directory
1678 * @param $userid int The user id
1679 * @return string path to file area.
1681 function file_area($userid) {
1682 return make_upload_directory( $this->file_area_name($userid) );
1686 * Returns true if the student is allowed to submit
1688 * Checks that the assignment has started and, if the option to prevent late
1689 * submissions is set, also checks that the assignment has not yet closed.
1690 * @return boolean
1692 function isopen() {
1693 $time = time();
1694 if ($this->assignment->preventlate && $this->assignment->timedue) {
1695 return ($this->assignment->timeavailable <= $time && $time <= $this->assignment->timedue);
1696 } else {
1697 return ($this->assignment->timeavailable <= $time);
1702 * Return an outline of the user's interaction with the assignment
1704 * The default method prints the grade and timemodified
1705 * @param $user object
1706 * @return object with properties ->info and ->time
1708 function user_outline($user) {
1709 if ($submission = $this->get_submission($user->id)) {
1711 $result = new object();
1712 $result->info = get_string('grade').': '.$this->display_grade($submission->grade);
1713 $result->time = $submission->timemodified;
1714 return $result;
1716 return NULL;
1720 * Print complete information about the user's interaction with the assignment
1722 * @param $user object
1724 function user_complete($user) {
1725 if ($submission = $this->get_submission($user->id)) {
1726 if ($basedir = $this->file_area($user->id)) {
1727 if ($files = get_directory_list($basedir)) {
1728 $countfiles = count($files)." ".get_string("uploadedfiles", "assignment");
1729 foreach ($files as $file) {
1730 $countfiles .= "; $file";
1735 print_simple_box_start();
1736 echo get_string("lastmodified").": ";
1737 echo userdate($submission->timemodified);
1738 echo $this->display_lateness($submission->timemodified);
1740 $this->print_user_files($user->id);
1742 echo '<br />';
1744 if (empty($submission->timemarked)) {
1745 print_string("notgradedyet", "assignment");
1746 } else {
1747 $this->view_feedback($submission);
1750 print_simple_box_end();
1752 } else {
1753 print_string("notsubmittedyet", "assignment");
1758 * Return a string indicating how late a submission is
1760 * @param $timesubmitted int
1761 * @return string
1763 function display_lateness($timesubmitted) {
1764 return assignment_display_lateness($timesubmitted, $this->assignment->timedue);
1768 * Empty method stub for all delete actions.
1770 function delete() {
1771 //nothing by default
1772 redirect('view.php?id='.$this->cm->id);
1776 * Empty custom feedback grading form.
1778 function custom_feedbackform($submission, $return=false) {
1779 //nothing by default
1780 return '';
1784 * Add a get_coursemodule_info function in case any assignment type wants to add 'extra' information
1785 * for the course (see resource).
1787 * Given a course_module object, this function returns any "extra" information that may be needed
1788 * when printing this activity in a course listing. See get_array_of_activities() in course/lib.php.
1790 * @param $coursemodule object The coursemodule object (record).
1791 * @return object An object on information that the coures will know about (most noticeably, an icon).
1794 function get_coursemodule_info($coursemodule) {
1795 return false;
1799 * Plugin cron method - do not use $this here, create new assignment instances if needed.
1800 * @return void
1802 function cron() {
1803 //no plugin cron by default - override if needed
1806 } ////// End of the assignment_base class
1810 /// OTHER STANDARD FUNCTIONS ////////////////////////////////////////////////////////
1813 * Deletes an assignment instance
1815 * This is done by calling the delete_instance() method of the assignment type class
1817 function assignment_delete_instance($id){
1818 global $CFG;
1820 if (! $assignment = get_record('assignment', 'id', $id)) {
1821 return false;
1824 // fall back to base class if plugin missing
1825 $classfile = "$CFG->dirroot/mod/assignment/type/$assignment->assignmenttype/assignment.class.php";
1826 if (file_exists($classfile)) {
1827 require_once($classfile);
1828 $assignmentclass = "assignment_$assignment->assignmenttype";
1830 } else {
1831 debugging("Missing assignment plug-in: {$assignment->assignmenttype}. Using base class for deleting instead.");
1832 $assignmentclass = "assignment_base";
1835 $ass = new $assignmentclass();
1836 return $ass->delete_instance($assignment);
1841 * Updates an assignment instance
1843 * This is done by calling the update_instance() method of the assignment type class
1845 function assignment_update_instance($assignment){
1846 global $CFG;
1848 $assignment->assignmenttype = clean_param($assignment->assignmenttype, PARAM_SAFEDIR);
1850 require_once("$CFG->dirroot/mod/assignment/type/$assignment->assignmenttype/assignment.class.php");
1851 $assignmentclass = "assignment_$assignment->assignmenttype";
1852 $ass = new $assignmentclass();
1853 return $ass->update_instance($assignment);
1858 * Adds an assignment instance
1860 * This is done by calling the add_instance() method of the assignment type class
1862 function assignment_add_instance($assignment) {
1863 global $CFG;
1865 $assignment->assignmenttype = clean_param($assignment->assignmenttype, PARAM_SAFEDIR);
1867 require_once("$CFG->dirroot/mod/assignment/type/$assignment->assignmenttype/assignment.class.php");
1868 $assignmentclass = "assignment_$assignment->assignmenttype";
1869 $ass = new $assignmentclass();
1870 return $ass->add_instance($assignment);
1875 * Returns an outline of a user interaction with an assignment
1877 * This is done by calling the user_outline() method of the assignment type class
1879 function assignment_user_outline($course, $user, $mod, $assignment) {
1880 global $CFG;
1882 require_once("$CFG->dirroot/mod/assignment/type/$assignment->assignmenttype/assignment.class.php");
1883 $assignmentclass = "assignment_$assignment->assignmenttype";
1884 $ass = new $assignmentclass($mod->id, $assignment, $mod, $course);
1885 return $ass->user_outline($user);
1889 * Prints the complete info about a user's interaction with an assignment
1891 * This is done by calling the user_complete() method of the assignment type class
1893 function assignment_user_complete($course, $user, $mod, $assignment) {
1894 global $CFG;
1896 require_once("$CFG->dirroot/mod/assignment/type/$assignment->assignmenttype/assignment.class.php");
1897 $assignmentclass = "assignment_$assignment->assignmenttype";
1898 $ass = new $assignmentclass($mod->id, $assignment, $mod, $course);
1899 return $ass->user_complete($user);
1903 * Function to be run periodically according to the moodle cron
1905 * Finds all assignment notifications that have yet to be mailed out, and mails them
1907 function assignment_cron () {
1909 global $CFG, $USER;
1911 /// first execute all crons in plugins
1912 if ($plugins = get_list_of_plugins('mod/assignment/type')) {
1913 foreach ($plugins as $plugin) {
1914 require_once("$CFG->dirroot/mod/assignment/type/$plugin/assignment.class.php");
1915 $assignmentclass = "assignment_$plugin";
1916 $ass = new $assignmentclass();
1917 $ass->cron();
1921 /// Notices older than 1 day will not be mailed. This is to avoid the problem where
1922 /// cron has not been running for a long time, and then suddenly people are flooded
1923 /// with mail from the past few weeks or months
1925 $timenow = time();
1926 $endtime = $timenow - $CFG->maxeditingtime;
1927 $starttime = $endtime - 24 * 3600; /// One day earlier
1929 if ($submissions = assignment_get_unmailed_submissions($starttime, $endtime)) {
1931 $CFG->enablerecordcache = true; // We want all the caching we can get
1933 $realuser = clone($USER);
1935 foreach ($submissions as $key => $submission) {
1936 if (! set_field("assignment_submissions", "mailed", "1", "id", "$submission->id")) {
1937 echo "Could not update the mailed field for id $submission->id. Not mailed.\n";
1938 unset($submissions[$key]);
1942 $timenow = time();
1944 foreach ($submissions as $submission) {
1946 echo "Processing assignment submission $submission->id\n";
1948 if (! $user = get_record("user", "id", "$submission->userid")) {
1949 echo "Could not find user $post->userid\n";
1950 continue;
1953 if (! $course = get_record("course", "id", "$submission->course")) {
1954 echo "Could not find course $submission->course\n";
1955 continue;
1958 /// Override the language and timezone of the "current" user, so that
1959 /// mail is customised for the receiver.
1960 $USER = $user;
1961 course_setup($course);
1963 if (!has_capability('moodle/course:view', get_context_instance(CONTEXT_COURSE, $submission->course), $user->id)) {
1964 echo fullname($user)." not an active participant in " . format_string($course->shortname) . "\n";
1965 continue;
1968 if (! $teacher = get_record("user", "id", "$submission->teacher")) {
1969 echo "Could not find teacher $submission->teacher\n";
1970 continue;
1973 if (! $mod = get_coursemodule_from_instance("assignment", $submission->assignment, $course->id)) {
1974 echo "Could not find course module for assignment id $submission->assignment\n";
1975 continue;
1978 if (! $mod->visible) { /// Hold mail notification for hidden assignments until later
1979 continue;
1982 $strassignments = get_string("modulenameplural", "assignment");
1983 $strassignment = get_string("modulename", "assignment");
1985 $assignmentinfo = new object();
1986 $assignmentinfo->teacher = fullname($teacher);
1987 $assignmentinfo->assignment = format_string($submission->name,true);
1988 $assignmentinfo->url = "$CFG->wwwroot/mod/assignment/view.php?id=$mod->id";
1990 $postsubject = "$course->shortname: $strassignments: ".format_string($submission->name,true);
1991 $posttext = "$course->shortname -> $strassignments -> ".format_string($submission->name,true)."\n";
1992 $posttext .= "---------------------------------------------------------------------\n";
1993 $posttext .= get_string("assignmentmail", "assignment", $assignmentinfo)."\n";
1994 $posttext .= "---------------------------------------------------------------------\n";
1996 if ($user->mailformat == 1) { // HTML
1997 $posthtml = "<p><font face=\"sans-serif\">".
1998 "<a href=\"$CFG->wwwroot/course/view.php?id=$course->id\">$course->shortname</a> ->".
1999 "<a href=\"$CFG->wwwroot/mod/assignment/index.php?id=$course->id\">$strassignments</a> ->".
2000 "<a href=\"$CFG->wwwroot/mod/assignment/view.php?id=$mod->id\">".format_string($submission->name,true)."</a></font></p>";
2001 $posthtml .= "<hr /><font face=\"sans-serif\">";
2002 $posthtml .= "<p>".get_string("assignmentmailhtml", "assignment", $assignmentinfo)."</p>";
2003 $posthtml .= "</font><hr />";
2004 } else {
2005 $posthtml = "";
2008 if (! email_to_user($user, $teacher, $postsubject, $posttext, $posthtml)) {
2009 echo "Error: assignment cron: Could not send out mail for id $submission->id to user $user->id ($user->email)\n";
2013 $USER = $realuser;
2014 course_setup(SITEID); // reset cron user language, theme and timezone settings
2018 return true;
2022 * Return grade for given user or all users.
2024 * @param int $assignmentid id of assignment
2025 * @param int $userid optional user id, 0 means all users
2026 * @return array array of grades, false if none
2028 function assignment_get_user_grades($assignment, $userid=0) {
2029 global $CFG;
2031 $user = $userid ? "AND u.id = $userid" : "";
2033 $sql = "SELECT u.id, u.id AS userid, s.grade AS rawgrade, s.submissioncomment AS feedback, s.format AS feedbackformat
2034 FROM {$CFG->prefix}user u, {$CFG->prefix}assignment_submissions s
2035 WHERE u.id = s.userid AND s.assignment = $assignment->id
2036 $user";
2038 return get_records_sql($sql);
2042 * Update grades by firing grade_updated event
2044 * @param object $assignment null means all assignments
2045 * @param int $userid specific user only, 0 mean all
2047 function assignment_update_grades($assignment=null, $userid=0, $nullifnone=true) {
2048 global $CFG;
2049 if (!function_exists('grade_update')) { //workaround for buggy PHP versions
2050 require_once($CFG->libdir.'/gradelib.php');
2053 if ($assignment != null) {
2054 if ($grades = assignment_get_user_grades($assignment, $userid)) {
2055 foreach($grades as $k=>$v) {
2056 if ($v->rawgrade == -1) {
2057 $grades[$k]->rawgrade = null;
2060 assignment_grade_item_update($assignment);
2061 grade_update('mod/assignment', $assignment->courseid, 'mod', 'assignment', $assignment->id, 0, $grades);
2064 } else {
2065 $sql = "SELECT a.*, cm.idnumber as cmidnumber, a.course as courseid
2066 FROM {$CFG->prefix}assignment a, {$CFG->prefix}course_modules cm, {$CFG->prefix}modules m
2067 WHERE m.name='assignment' AND m.id=cm.module AND cm.instance=a.id";
2068 if ($rs = get_recordset_sql($sql)) {
2069 if ($rs->RecordCount() > 0) {
2070 while ($assignment = rs_fetch_next_record($rs)) {
2071 assignment_grade_item_update($assignment);
2072 if ($assignment->grade != 0) {
2073 assignment_update_grades($assignment);
2077 rs_close($rs);
2083 * Create grade item for given assignment
2085 * @param object $assignment object with extra cmidnumber
2086 * @return int 0 if ok, error code otherwise
2088 function assignment_grade_item_update($assignment) {
2089 global $CFG;
2090 if (!function_exists('grade_update')) { //workaround for buggy PHP versions
2091 require_once($CFG->libdir.'/gradelib.php');
2094 if (!isset($assignment->courseid)) {
2095 $assignment->courseid = $assignment->course;
2098 $params = array('itemname'=>$assignment->name, 'idnumber'=>$assignment->cmidnumber);
2100 if ($assignment->grade > 0) {
2101 $params['gradetype'] = GRADE_TYPE_VALUE;
2102 $params['grademax'] = $assignment->grade;
2103 $params['grademin'] = 0;
2105 } else if ($assignment->grade < 0) {
2106 $params['gradetype'] = GRADE_TYPE_SCALE;
2107 $params['scaleid'] = -$assignment->grade;
2109 } else {
2110 $params['gradetype'] = GRADE_TYPE_NONE;
2113 return grade_update('mod/assignment', $assignment->courseid, 'mod', 'assignment', $assignment->id, 0, NULL, $params);
2117 * Delete grade item for given assignment
2119 * @param object $assignment object
2120 * @return object assignment
2122 function assignment_grade_item_delete($assignment) {
2123 global $CFG;
2124 require_once($CFG->libdir.'/gradelib.php');
2126 if (!isset($assignment->courseid)) {
2127 $assignment->courseid = $assignment->course;
2130 return grade_update('mod/assignment', $assignment->courseid, 'mod', 'assignment', $assignment->id, 0, NULL, array('deleted'=>1));
2134 * Gradebook informs this module about new grade or feedback.
2137 function assignment_grade_updated($instance, $itemnumber, $userid, $gradevalue, $feedback, $feedbackformat, $usermodified) {
2138 global $CFG, $USER;
2140 if (!$assignment = get_record('assignment', 'id', $instance)) {
2141 return true;
2143 if (! $course = get_record('course', 'id', $assignment->course)) {
2144 return true;
2146 if (! $cm = get_coursemodule_from_instance('assignment', $assignment->id, $course->id)) {
2147 return true;
2150 // Load up the required assignment class
2151 require_once($CFG->dirroot.'/mod/assignment/type/'.$assignment->assignmenttype.'/assignment.class.php');
2152 $assignmentclass = 'assignment_'.$assignment->assignmenttype;
2153 $assignmentinstance = new $assignmentclass($cm->id, $assignment, $cm, $course);
2155 $old = $assignmentinstance->get_submission($userid, true); // Get or make one
2156 $submission = new object();
2157 $submission->id = $old->id;
2158 $submission->userid = $old->userid;
2159 $submission->teacher = $usermodified;
2161 if ($gradevalue === false) {
2162 $submission->grade = $old->grade;
2163 } else if (is_null($gradevalue)) {
2164 $submission->grade = -1;
2165 } else {
2166 $submission->grade = (int)$gradevalue; // round it for now
2167 $submission->timemarked = time();
2170 if ($feedback === false) {
2171 $submission->submissioncomment = addslashes($old->submissioncomment);
2172 $submission->format = $old->format;
2173 } else {
2174 $submission->submissioncomment = addslashes($feedback);
2175 $submission->format = (int)$feedbackformat;
2178 if ($old->submissioncomment != $submission->submissioncomment or $old->grade != $submission->grade) {
2180 $submission->mailed = 0; // Make sure mail goes out (again, even)
2182 if (!update_record('assignment_submissions', $submission)) {
2183 return false;
2187 // TODO: add proper logging
2188 add_to_log($course->id, 'assignment', 'update grades',
2189 'submissions.php?id='.$assignment->id.'&user='.$submission->userid, $submission->userid, $cm->id);
2191 return true;
2195 * Returns the users with data in one assignment (students and teachers)
2197 * @param $assignmentid int
2198 * @return array of user objects
2200 function assignment_get_participants($assignmentid) {
2202 global $CFG;
2204 //Get students
2205 $students = get_records_sql("SELECT DISTINCT u.id, u.id
2206 FROM {$CFG->prefix}user u,
2207 {$CFG->prefix}assignment_submissions a
2208 WHERE a.assignment = '$assignmentid' and
2209 u.id = a.userid");
2210 //Get teachers
2211 $teachers = get_records_sql("SELECT DISTINCT u.id, u.id
2212 FROM {$CFG->prefix}user u,
2213 {$CFG->prefix}assignment_submissions a
2214 WHERE a.assignment = '$assignmentid' and
2215 u.id = a.teacher");
2217 //Add teachers to students
2218 if ($teachers) {
2219 foreach ($teachers as $teacher) {
2220 $students[$teacher->id] = $teacher;
2223 //Return students array (it contains an array of unique users)
2224 return ($students);
2228 * Checks if a scale is being used by an assignment
2230 * This is used by the backup code to decide whether to back up a scale
2231 * @param $assignmentid int
2232 * @param $scaleid int
2233 * @return boolean True if the scale is used by the assignment
2235 function assignment_scale_used ($assignmentid, $scaleid) {
2237 $return = false;
2239 $rec = get_record('assignment','id',$assignmentid,'grade',-$scaleid);
2241 if (!empty($rec) && !empty($scaleid)) {
2242 $return = true;
2245 return $return;
2249 * Make sure up-to-date events are created for all assignment instances
2251 * This standard function will check all instances of this module
2252 * and make sure there are up-to-date events created for each of them.
2253 * If courseid = 0, then every assignment event in the site is checked, else
2254 * only assignment events belonging to the course specified are checked.
2255 * This function is used, in its new format, by restore_refresh_events()
2257 * @param $courseid int optional If zero then all assignments for all courses are covered
2258 * @return boolean Always returns true
2260 function assignment_refresh_events($courseid = 0) {
2262 if ($courseid == 0) {
2263 if (! $assignments = get_records("assignment")) {
2264 return true;
2266 } else {
2267 if (! $assignments = get_records("assignment", "course", $courseid)) {
2268 return true;
2271 $moduleid = get_field('modules', 'id', 'name', 'assignment');
2273 foreach ($assignments as $assignment) {
2274 $event = NULL;
2275 $event->name = addslashes($assignment->name);
2276 $event->description = addslashes($assignment->description);
2277 $event->timestart = $assignment->timedue;
2279 if ($event->id = get_field('event', 'id', 'modulename', 'assignment', 'instance', $assignment->id)) {
2280 update_event($event);
2282 } else {
2283 $event->courseid = $assignment->course;
2284 $event->groupid = 0;
2285 $event->userid = 0;
2286 $event->modulename = 'assignment';
2287 $event->instance = $assignment->id;
2288 $event->eventtype = 'due';
2289 $event->timeduration = 0;
2290 $event->visible = get_field('course_modules', 'visible', 'module', $moduleid, 'instance', $assignment->id);
2291 add_event($event);
2295 return true;
2299 * Print recent activity from all assignments in a given course
2301 * This is used by the recent activity block
2303 function assignment_print_recent_activity($course, $isteacher, $timestart) {
2304 global $CFG;
2306 $content = false;
2307 $assignments = array();
2309 if (!$logs = get_records_select('log', 'time > \''.$timestart.'\' AND '.
2310 'course = \''.$course->id.'\' AND '.
2311 'module = \'assignment\' AND '.
2312 'action = \'upload\' ', 'time ASC')) {
2313 return false;
2316 foreach ($logs as $log) {
2317 //Create a temp valid module structure (course,id)
2318 $tempmod = new object();
2319 $tempmod->course = $log->course;
2320 $tempmod->id = $log->info;
2321 //Obtain the visible property from the instance
2322 $modvisible = instance_is_visible($log->module,$tempmod);
2324 //Only if the mod is visible
2325 if ($modvisible) {
2326 if ($info = assignment_log_info($log)) {
2327 $assignments[$log->info] = $info;
2328 $assignments[$log->info]->time = $log->time;
2329 $assignments[$log->info]->url = str_replace('&', '&amp;', $log->url);
2334 if (!empty($assignments)) {
2335 print_headline(get_string('newsubmissions', 'assignment').':');
2336 foreach ($assignments as $assignment) {
2337 print_recent_activity_note($assignment->time, $assignment, $assignment->name,
2338 $CFG->wwwroot.'/mod/assignment/'.$assignment->url);
2340 $content = true;
2343 return $content;
2348 * Returns all assignments since a given time.
2350 * If assignment is specified then this restricts the results
2352 function assignment_get_recent_mod_activity(&$activities, &$index, $sincetime, $courseid, $assignment="0", $user="", $groupid="") {
2354 global $CFG;
2356 if ($assignment) {
2357 $assignmentselect = " AND cm.id = '$assignment'";
2358 } else {
2359 $assignmentselect = "";
2361 if ($user) {
2362 $userselect = " AND u.id = '$user'";
2363 } else {
2364 $userselect = "";
2367 $assignments = get_records_sql("SELECT asub.*, u.firstname, u.lastname, u.picture, u.id as userid,
2368 a.grade as maxgrade, name, cm.instance, cm.section, a.assignmenttype
2369 FROM {$CFG->prefix}assignment_submissions asub,
2370 {$CFG->prefix}user u,
2371 {$CFG->prefix}assignment a,
2372 {$CFG->prefix}course_modules cm
2373 WHERE asub.timemodified > '$sincetime'
2374 AND asub.userid = u.id $userselect
2375 AND a.id = asub.assignment $assignmentselect
2376 AND cm.course = '$courseid'
2377 AND cm.instance = a.id
2378 ORDER BY asub.timemodified ASC");
2380 if (empty($assignments))
2381 return;
2383 foreach ($assignments as $assignment) {
2384 if (empty($groupid) || groups_is_member($groupid, $assignment->userid)) {
2386 $tmpactivity = new Object;
2388 $tmpactivity->type = "assignment";
2389 $tmpactivity->defaultindex = $index;
2390 $tmpactivity->instance = $assignment->instance;
2391 $tmpactivity->name = $assignment->name;
2392 $tmpactivity->section = $assignment->section;
2394 $tmpactivity->content->grade = $assignment->grade;
2395 $tmpactivity->content->maxgrade = $assignment->maxgrade;
2396 $tmpactivity->content->type = $assignment->assignmenttype;
2398 $tmpactivity->user->userid = $assignment->userid;
2399 $tmpactivity->user->fullname = fullname($assignment);
2400 $tmpactivity->user->picture = $assignment->picture;
2402 $tmpactivity->timestamp = $assignment->timemodified;
2404 $activities[] = $tmpactivity;
2406 $index++;
2410 return;
2414 * Print recent activity from all assignments in a given course
2416 * This is used by course/recent.php
2418 function assignment_print_recent_mod_activity($activity, $course, $detail=false) {
2419 global $CFG;
2421 echo '<table border="0" cellpadding="3" cellspacing="0">';
2423 echo "<tr><td class=\"userpicture\" valign=\"top\">";
2424 print_user_picture($activity->user->userid, $course, $activity->user->picture);
2425 echo "</td><td width=\"100%\"><font size=2>";
2427 if ($detail) {
2428 echo "<img src=\"$CFG->modpixpath/$activity->type/icon.gif\" ".
2429 "class=\"icon\" alt=\"$activity->type\"> ";
2430 echo "<a href=\"$CFG->wwwroot/mod/assignment/view.php?id=" . $activity->instance . "\">"
2431 . format_string($activity->name,true) . "</a> - ";
2435 if (has_capability('moodle/course:viewrecent', get_context_instance(CONTEXT_COURSE, $course))) {
2436 $grades = "(" . $activity->content->grade . " / " . $activity->content->maxgrade . ") ";
2438 $assignment->id = $activity->instance;
2439 $assignment->course = $course;
2440 $user->id = $activity->user->userid;
2442 echo $grades;
2443 echo "<br />";
2445 echo "<a href=\"$CFG->wwwroot/user/view.php?id="
2446 . $activity->user->userid . "&amp;course=$course\">"
2447 . $activity->user->fullname . "</a> ";
2449 echo " - " . userdate($activity->timestamp);
2451 echo "</font></td></tr>";
2452 echo "</table>";
2455 /// GENERIC SQL FUNCTIONS
2458 * Fetch info from logs
2460 * @param $log object with properties ->info (the assignment id) and ->userid
2461 * @return array with assignment name and user firstname and lastname
2463 function assignment_log_info($log) {
2464 global $CFG;
2465 return get_record_sql("SELECT a.name, u.firstname, u.lastname
2466 FROM {$CFG->prefix}assignment a,
2467 {$CFG->prefix}user u
2468 WHERE a.id = '$log->info'
2469 AND u.id = '$log->userid'");
2473 * Return list of marked submissions that have not been mailed out for currently enrolled students
2475 * @return array
2477 function assignment_get_unmailed_submissions($starttime, $endtime) {
2479 global $CFG;
2481 return get_records_sql("SELECT s.*, a.course, a.name
2482 FROM {$CFG->prefix}assignment_submissions s,
2483 {$CFG->prefix}assignment a
2484 WHERE s.mailed = 0
2485 AND s.timemarked <= $endtime
2486 AND s.timemarked >= $starttime
2487 AND s.assignment = a.id");
2489 /* return get_records_sql("SELECT s.*, a.course, a.name
2490 FROM {$CFG->prefix}assignment_submissions s,
2491 {$CFG->prefix}assignment a,
2492 {$CFG->prefix}user_students us
2493 WHERE s.mailed = 0
2494 AND s.timemarked <= $endtime
2495 AND s.timemarked >= $starttime
2496 AND s.assignment = a.id
2497 AND s.userid = us.userid
2498 AND a.course = us.course");
2503 * Counts all real assignment submissions by ENROLLED students (not empty ones)
2505 * There are also assignment type methods count_real_submissions() wich in the default
2506 * implementation simply call this function.
2507 * @param $groupid int optional If nonzero then count is restricted to this group
2508 * @return int The number of submissions
2510 function assignment_count_real_submissions($assignment, $groupid=0) {
2511 global $CFG;
2513 if ($groupid) { /// How many in a particular group?
2514 return count_records_sql("SELECT COUNT(DISTINCT gm.userid, gm.groupid)
2515 FROM {$CFG->prefix}assignment_submissions a,
2516 {$CFG->prefix}groups_members g
2517 WHERE a.assignment = $assignment->id
2518 AND a.timemodified > 0
2519 AND g.groupid = '$groupid'
2520 AND a.userid = g.userid ");
2521 } else {
2522 $cm = get_coursemodule_from_instance('assignment', $assignment->id);
2523 $context = get_context_instance(CONTEXT_MODULE, $cm->id);
2525 // this is all the users with this capability set, in this context or higher
2526 if ($users = get_users_by_capability($context, 'mod/assignment:submit', '', '', '', '', 0, '', false)) {
2527 foreach ($users as $user) {
2528 $array[] = $user->id;
2531 $userlists = '('.implode(',',$array).')';
2533 return count_records_sql("SELECT COUNT(*)
2534 FROM {$CFG->prefix}assignment_submissions
2535 WHERE assignment = '$assignment->id'
2536 AND timemodified > 0
2537 AND userid IN $userlists ");
2538 } else {
2539 return 0; // no users enroled in course
2546 * Return all assignment submissions by ENROLLED students (even empty)
2548 * There are also assignment type methods get_submissions() wich in the default
2549 * implementation simply call this function.
2550 * @param $sort string optional field names for the ORDER BY in the sql query
2551 * @param $dir string optional specifying the sort direction, defaults to DESC
2552 * @return array The submission objects indexed by id
2554 function assignment_get_all_submissions($assignment, $sort="", $dir="DESC") {
2555 /// Return all assignment submissions by ENROLLED students (even empty)
2556 global $CFG;
2558 if ($sort == "lastname" or $sort == "firstname") {
2559 $sort = "u.$sort $dir";
2560 } else if (empty($sort)) {
2561 $sort = "a.timemodified DESC";
2562 } else {
2563 $sort = "a.$sort $dir";
2566 /* not sure this is needed at all since assignmenet already has a course define, so this join?
2567 $select = "s.course = '$assignment->course' AND";
2568 if ($assignment->course == SITEID) {
2569 $select = '';
2572 return get_records_sql("SELECT a.*
2573 FROM {$CFG->prefix}assignment_submissions a,
2574 {$CFG->prefix}user u
2575 WHERE u.id = a.userid
2576 AND a.assignment = '$assignment->id'
2577 ORDER BY $sort");
2579 /* return get_records_sql("SELECT a.*
2580 FROM {$CFG->prefix}assignment_submissions a,
2581 {$CFG->prefix}user_students s,
2582 {$CFG->prefix}user u
2583 WHERE a.userid = s.userid
2584 AND u.id = a.userid
2585 AND $select a.assignment = '$assignment->id'
2586 ORDER BY $sort");
2591 * Add a get_coursemodule_info function in case any assignment type wants to add 'extra' information
2592 * for the course (see resource).
2594 * Given a course_module object, this function returns any "extra" information that may be needed
2595 * when printing this activity in a course listing. See get_array_of_activities() in course/lib.php.
2597 * @param $coursemodule object The coursemodule object (record).
2598 * @return object An object on information that the coures will know about (most noticeably, an icon).
2601 function assignment_get_coursemodule_info($coursemodule) {
2602 global $CFG;
2604 if (! $assignment = get_record('assignment', 'id', $coursemodule->instance)) {
2605 return false;
2608 require_once("$CFG->dirroot/mod/assignment/type/$assignment->assignmenttype/assignment.class.php");
2609 $assignmentclass = "assignment_$assignment->assignmenttype";
2610 $ass = new $assignmentclass($coursemodule->id, $assignment);
2612 return $ass->get_coursemodule_info($coursemodule);
2617 /// OTHER GENERAL FUNCTIONS FOR ASSIGNMENTS ///////////////////////////////////////
2620 * Returns an array of installed assignment types indexed and sorted by name
2622 * @return array The index is the name of the assignment type, the value its full name from the language strings
2624 function assignment_types() {
2625 $types = array();
2626 $names = get_list_of_plugins('mod/assignment/type');
2627 foreach ($names as $name) {
2628 $types[$name] = get_string('type'.$name, 'assignment');
2630 asort($types);
2631 return $types;
2635 * Executes upgrade scripts for assignment types when necessary
2637 function assignment_upgrade_submodules() {
2639 global $CFG;
2641 /// Install/upgrade assignment types (it uses, simply, the standard plugin architecture)
2642 upgrade_plugins('assignment_type', 'mod/assignment/type', "$CFG->wwwroot/$CFG->admin/index.php");
2646 function assignment_print_overview($courses, &$htmlarray) {
2648 global $USER, $CFG;
2650 if (empty($courses) || !is_array($courses) || count($courses) == 0) {
2651 return array();
2654 if (!$assignments = get_all_instances_in_courses('assignment',$courses)) {
2655 return;
2658 // Do assignment_base::isopen() here without loading the whole thing for speed
2659 foreach ($assignments as $key => $assignment) {
2660 $time = time();
2661 if ($assignment->timedue) {
2662 if ($assignment->preventlate) {
2663 $isopen = ($assignment->timeavailable <= $time && $time <= $assignment->timedue);
2664 } else {
2665 $isopen = ($assignment->timeavailable <= $time);
2668 if (empty($isopen) || empty($assignment->timedue)) {
2669 unset($assignments[$key]);
2673 $strduedate = get_string('duedate', 'assignment');
2674 $strduedateno = get_string('duedateno', 'assignment');
2675 $strgraded = get_string('graded', 'assignment');
2676 $strnotgradedyet = get_string('notgradedyet', 'assignment');
2677 $strnotsubmittedyet = get_string('notsubmittedyet', 'assignment');
2678 $strsubmitted = get_string('submitted', 'assignment');
2679 $strassignment = get_string('modulename', 'assignment');
2680 $strreviewed = get_string('reviewed','assignment');
2682 foreach ($assignments as $assignment) {
2683 $str = '<div class="assignment overview"><div class="name">'.$strassignment. ': '.
2684 '<a '.($assignment->visible ? '':' class="dimmed"').
2685 'title="'.$strassignment.'" href="'.$CFG->wwwroot.
2686 '/mod/assignment/view.php?id='.$assignment->coursemodule.'">'.
2687 $assignment->name.'</a></div>';
2688 if ($assignment->timedue) {
2689 $str .= '<div class="info">'.$strduedate.': '.userdate($assignment->timedue).'</div>';
2690 } else {
2691 $str .= '<div class="info">'.$strduedateno.'</div>';
2693 $context = get_context_instance(CONTEXT_MODULE, $assignment->coursemodule);
2694 if (has_capability('mod/assignment:grade', $context)) {
2696 // count how many people can submit
2697 $submissions = 0; // init
2698 if ($students = get_users_by_capability($context, 'mod/assignment:submit', '', '', '', '', 0, '', false)) {
2699 foreach ($students as $student) {
2700 if (get_records_sql("SELECT id,id FROM {$CFG->prefix}assignment_submissions
2701 WHERE assignment = $assignment->id AND
2702 userid = $student->id AND
2703 teacher = 0 AND
2704 timemarked = 0")) {
2705 $submissions++;
2710 if ($submissions) {
2711 $str .= get_string('submissionsnotgraded', 'assignment', $submissions);
2713 } else {
2714 $sql = "SELECT *
2715 FROM {$CFG->prefix}assignment_submissions
2716 WHERE userid = '$USER->id'
2717 AND assignment = '{$assignment->id}'";
2718 if ($submission = get_record_sql($sql)) {
2719 if ($submission->teacher == 0 && $submission->timemarked == 0) {
2720 $str .= $strsubmitted . ', ' . $strnotgradedyet;
2721 } else if ($submission->grade <= 0) {
2722 $str .= $strsubmitted . ', ' . $strreviewed;
2723 } else {
2724 $str .= $strsubmitted . ', ' . $strgraded;
2726 } else {
2727 $str .= $strnotsubmittedyet . ' ' . assignment_display_lateness(time(), $assignment->timedue);
2730 $str .= '</div>';
2731 if (empty($htmlarray[$assignment->course]['assignment'])) {
2732 $htmlarray[$assignment->course]['assignment'] = $str;
2733 } else {
2734 $htmlarray[$assignment->course]['assignment'] .= $str;
2739 function assignment_display_lateness($timesubmitted, $timedue) {
2740 if (!$timedue) {
2741 return '';
2743 $time = $timedue - $timesubmitted;
2744 if ($time < 0) {
2745 $timetext = get_string('late', 'assignment', format_time($time));
2746 return ' (<span class="late">'.$timetext.'</span>)';
2747 } else {
2748 $timetext = get_string('early', 'assignment', format_time($time));
2749 return ' (<span class="early">'.$timetext.'</span>)';
2753 function assignment_get_view_actions() {
2754 return array('view');
2757 function assignment_get_post_actions() {
2758 return array('upload');
2761 function assignment_get_types() {
2762 global $CFG;
2763 $types = array();
2765 $type = new object();
2766 $type->modclass = MOD_CLASS_ACTIVITY;
2767 $type->type = "assignment_group_start";
2768 $type->typestr = '--'.get_string('modulenameplural', 'assignment');
2769 $types[] = $type;
2771 $standardassignments = array('upload','online','uploadsingle','offline');
2772 foreach ($standardassignments as $assignmenttype) {
2773 $type = new object();
2774 $type->modclass = MOD_CLASS_ACTIVITY;
2775 $type->type = "assignment&amp;type=$assignmenttype";
2776 $type->typestr = get_string("type$assignmenttype", 'assignment');
2777 $types[] = $type;
2780 /// Drop-in extra assignment types
2781 $assignmenttypes = get_list_of_plugins('mod/assignment/type');
2782 foreach ($assignmenttypes as $assignmenttype) {
2783 if (!empty($CFG->{'assignment_hide_'.$assignmenttype})) { // Not wanted
2784 continue;
2786 if (!in_array($assignmenttype, $standardassignments)) {
2787 $type = new object();
2788 $type->modclass = MOD_CLASS_ACTIVITY;
2789 $type->type = "assignment&amp;type=$assignmenttype";
2790 $type->typestr = get_string("type$assignmenttype", 'assignment');
2791 $types[] = $type;
2795 $type = new object();
2796 $type->modclass = MOD_CLASS_ACTIVITY;
2797 $type->type = "assignment_group_end";
2798 $type->typestr = '--';
2799 $types[] = $type;
2801 return $types;