3 // This file is part of Moodle - http://moodle.org/
5 // Moodle is free software: you can redistribute it and/or modify
6 // it under the terms of the GNU General Public License as published by
7 // the Free Software Foundation, either version 3 of the License, or
8 // (at your option) any later version.
10 // Moodle is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 // GNU General Public License for more details.
15 // You should have received a copy of the GNU General Public License
16 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
19 * assignment_base is the base class for assignment types
21 * This class provides all the functionality for an assignment
23 * @package mod-assignment
24 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
25 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
28 /** Include eventslib.php */
29 require_once($CFG->libdir.'/eventslib.php');
30 /** Include formslib.php */
31 require_once($CFG->libdir.'/formslib.php');
32 /** Include calendar/lib.php */
33 require_once($CFG->dirroot.'/calendar/lib.php');
35 /** ASSIGNMENT_COUNT_WORDS = 1 */
36 DEFINE ('ASSIGNMENT_COUNT_WORDS', 1);
37 /** ASSIGNMENT_COUNT_LETTERS = 2 */
38 DEFINE ('ASSIGNMENT_COUNT_LETTERS', 2);
41 * Standard base class for all assignment submodules (assignment types).
43 * @package mod-assignment
44 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
45 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
47 class assignment_base {
68 * @todo document this var
72 * @todo document this var
79 * Constructor for the base assignment class
81 * Constructor for the base assignment class.
82 * If cmid is set create the cm, course, assignment objects.
83 * If the assignment is hidden and the user is not a teacher then
84 * this prints a page header and notice.
88 * @param int $cmid the current course module id - not set for new assignments
89 * @param object $assignment usually null, but if we have it we pass it to save db access
90 * @param object $cm usually null, but if we have it we pass it to save db access
91 * @param object $course usually null, but if we have it we pass it to save db access
93 function assignment_base($cmid='staticonly', $assignment=NULL, $cm=NULL, $course=NULL) {
96 if ($cmid == 'staticonly') {
97 //use static functions only!
105 } else if (! $this->cm = get_coursemodule_from_id('assignment', $cmid)) {
106 print_error('invalidcoursemodule');
109 $this->context = get_context_instance(CONTEXT_MODULE, $this->cm->id);
112 $this->course = $course;
113 } else if ($this->cm->course == $COURSE->id) {
114 $this->course = $COURSE;
115 } else if (! $this->course = $DB->get_record('course', array('id'=>$this->cm->course))) {
116 print_error('invalidid', 'assignment');
120 $this->assignment = $assignment;
121 } else if (! $this->assignment = $DB->get_record('assignment', array('id'=>$this->cm->instance))) {
122 print_error('invalidid', 'assignment');
125 $this->assignment->cmidnumber = $this->cm->idnumber; // compatibility with modedit assignment obj
126 $this->assignment->courseid = $this->course->id; // compatibility with modedit assignment obj
128 $this->strassignment = get_string('modulename', 'assignment');
129 $this->strassignments = get_string('modulenameplural', 'assignment');
130 $this->strsubmissions = get_string('submissions', 'assignment');
131 $this->strlastmodified = get_string('lastmodified');
132 $this->pagetitle = strip_tags($this->course->shortname.': '.$this->strassignment.': '.format_string($this->assignment->name,true));
134 // visibility handled by require_login() with $cm parameter
135 // get current group only when really needed
137 /// Set up things for a HTML editor if it's needed
138 if ($this->usehtmleditor = can_use_html_editor()) {
139 $this->defaultformat = FORMAT_HTML;
141 $this->defaultformat = FORMAT_MOODLE;
146 * Display the assignment, used by view.php
148 * This in turn calls the methods producing individual parts of the page
152 $context = get_context_instance(CONTEXT_MODULE,$this->cm->id);
153 require_capability('mod/assignment:view', $context);
155 add_to_log($this->course->id, "assignment", "view", "view.php?id={$this->cm->id}",
156 $this->assignment->id, $this->cm->id);
158 $this->view_header();
164 $this->view_feedback();
166 $this->view_footer();
170 * Display the header and top of a page
172 * (this doesn't change much for assignment types)
173 * This is used by the view() method to print the header of view.php but
174 * it can be used on other pages in which case the string to denote the
175 * page in the navigation trail should be passed as an argument
178 * @param string $subpage Description of subpage to be used in navigation trail
180 function view_header($subpage='') {
181 global $CFG, $PAGE, $OUTPUT;
184 $PAGE->navbar->add($subpage);
187 $PAGE->set_title($this->pagetitle);
188 $PAGE->set_heading($this->course->fullname);
190 echo $OUTPUT->header();
192 groups_print_activity_menu($this->cm, $CFG->wwwroot . '/mod/assignment/view.php?id=' . $this->cm->id);
194 echo '<div class="reportlink">'.$this->submittedlink().'</div>';
195 echo '<div class="clearer"></div>';
200 * Display the assignment intro
202 * This will most likely be extended by assignment type plug-ins
203 * The default implementation prints the assignment description in a box
205 function view_intro() {
207 echo $OUTPUT->box_start('generalbox boxaligncenter', 'intro');
208 echo format_module_intro('assignment', $this->assignment, $this->cm->id);
209 echo $OUTPUT->box_end();
213 * Display the assignment dates
215 * Prints the assignment start and end dates in a box.
216 * This will be suitable for most assignment types
218 function view_dates() {
220 if (!$this->assignment->timeavailable && !$this->assignment->timedue) {
224 echo $OUTPUT->box_start('generalbox boxaligncenter', 'dates');
226 if ($this->assignment->timeavailable) {
227 echo '<tr><td class="c0">'.get_string('availabledate','assignment').':</td>';
228 echo ' <td class="c1">'.userdate($this->assignment->timeavailable).'</td></tr>';
230 if ($this->assignment->timedue) {
231 echo '<tr><td class="c0">'.get_string('duedate','assignment').':</td>';
232 echo ' <td class="c1">'.userdate($this->assignment->timedue).'</td></tr>';
235 echo $OUTPUT->box_end();
240 * Display the bottom and footer of a page
242 * This default method just prints the footer.
243 * This will be suitable for most assignment types
245 function view_footer() {
247 echo $OUTPUT->footer();
251 * Display the feedback to the student
253 * This default method prints the teacher picture and name, date when marked,
254 * grade and teacher submissioncomment.
259 * @param object $submission The submission object or NULL in which case it will be loaded
261 function view_feedback($submission=NULL) {
262 global $USER, $CFG, $DB, $OUTPUT;
263 require_once($CFG->libdir.'/gradelib.php');
265 if (!is_enrolled($this->context, $USER, 'mod/assignment:submit')) {
266 // can not submit assignments -> no feedback
270 if (!$submission) { /// Get submission for this assignment
271 $submission = $this->get_submission($USER->id);
274 $grading_info = grade_get_grades($this->course->id, 'mod', 'assignment', $this->assignment->id, $USER->id);
275 $item = $grading_info->items[0];
276 $grade = $item->grades[$USER->id];
278 if ($grade->hidden or $grade->grade === false) { // hidden or error
282 if ($grade->grade === null and empty($grade->str_feedback)) { /// Nothing to show yet
286 $graded_date = $grade->dategraded;
287 $graded_by = $grade->usermodified;
289 /// We need the teacher info
290 if (!$teacher = $DB->get_record('user', array('id'=>$graded_by))) {
291 print_error('cannotfindteacher');
294 /// Print the feedback
295 echo $OUTPUT->heading(get_string('feedbackfromteacher', 'assignment', fullname($teacher)));
297 echo '<table cellspacing="0" class="feedback">';
300 echo '<td class="left picture">';
302 echo $OUTPUT->user_picture($teacher);
305 echo '<td class="topic">';
306 echo '<div class="from">';
308 echo '<div class="fullname">'.fullname($teacher).'</div>';
310 echo '<div class="time">'.userdate($graded_date).'</div>';
316 echo '<td class="left side"> </td>';
317 echo '<td class="content">';
318 echo '<div class="grade">';
319 echo get_string("grade").': '.$grade->str_long_grade;
321 echo '<div class="clearer"></div>';
323 echo '<div class="comment">';
324 echo $grade->str_feedback;
332 * Returns a link with info about the state of the assignment submissions
334 * This is used by view_header to put this link at the top right of the page.
335 * For teachers it gives the number of submitted assignments with a link
336 * For students it gives the time of their submission.
337 * This will be suitable for most assignment types.
341 * @param bool $allgroup print all groups info if user can access all groups, suitable for index.php
344 function submittedlink($allgroups=false) {
349 $urlbase = "{$CFG->wwwroot}/mod/assignment/";
351 $context = get_context_instance(CONTEXT_MODULE,$this->cm->id);
352 if (has_capability('mod/assignment:grade', $context)) {
353 if ($allgroups and has_capability('moodle/site:accessallgroups', $context)) {
356 $group = groups_get_activity_group($this->cm);
358 if ($count = $this->count_real_submissions($group)) {
359 $submitted = '<a href="'.$urlbase.'submissions.php?id='.$this->cm->id.'">'.
360 get_string('viewsubmissions', 'assignment', $count).'</a>';
362 $submitted = '<a href="'.$urlbase.'submissions.php?id='.$this->cm->id.'">'.
363 get_string('noattempts', 'assignment').'</a>';
367 if ($submission = $this->get_submission($USER->id)) {
368 if ($submission->timemodified) {
369 if ($submission->timemodified <= $this->assignment->timedue || empty($this->assignment->timedue)) {
370 $submitted = '<span class="early">'.userdate($submission->timemodified).'</span>';
372 $submitted = '<span class="late">'.userdate($submission->timemodified).'</span>';
384 * @todo Document this function
386 function setup_elements(&$mform) {
391 * Create a new assignment activity
393 * Given an object containing all the necessary data,
394 * (defined by the form in mod_form.php) this function
395 * will create a new instance and return the id number
396 * of the new instance.
397 * The due data is added to the calendar
398 * This is common to all assignment types.
402 * @param object $assignment The data from the form on mod_form.php
403 * @return int The id of the assignment
405 function add_instance($assignment) {
408 $assignment->timemodified = time();
409 $assignment->courseid = $assignment->course;
411 if ($returnid = $DB->insert_record("assignment", $assignment)) {
412 $assignment->id = $returnid;
414 if ($assignment->timedue) {
415 $event = new object();
416 $event->name = $assignment->name;
417 $event->description = format_module_intro('assignment', $assignment, $assignment->coursemodule);
418 $event->courseid = $assignment->course;
421 $event->modulename = 'assignment';
422 $event->instance = $returnid;
423 $event->eventtype = 'due';
424 $event->timestart = $assignment->timedue;
425 $event->timeduration = 0;
427 calendar_event::create($event);
430 assignment_grade_item_update($assignment);
439 * Deletes an assignment activity
441 * Deletes all database records, files and calendar events for this assignment.
445 * @param object $assignment The assignment to be deleted
446 * @return boolean False indicates error
448 function delete_instance($assignment) {
451 $assignment->courseid = $assignment->course;
455 // now get rid of all files
456 $fs = get_file_storage();
457 if ($cm = get_coursemodule_from_instance('assignment', $assignment->id)) {
458 $context = get_context_instance(CONTEXT_MODULE, $cm->id);
459 $fs->delete_area_files($context->id);
462 if (! $DB->delete_records('assignment_submissions', array('assignment'=>$assignment->id))) {
466 if (! $DB->delete_records('event', array('modulename'=>'assignment', 'instance'=>$assignment->id))) {
470 if (! $DB->delete_records('assignment', array('id'=>$assignment->id))) {
473 $mod = $DB->get_field('modules','id',array('name'=>'assignment'));
475 assignment_grade_item_delete($assignment);
481 * Updates a new assignment activity
483 * Given an object containing all the necessary data,
484 * (defined by the form in mod_form.php) this function
485 * will update the assignment instance and return the id number
486 * The due date is updated in the calendar
487 * This is common to all assignment types.
491 * @param object $assignment The data from the form on mod_form.php
492 * @return int The assignment id
494 function update_instance($assignment) {
497 $assignment->timemodified = time();
499 $assignment->id = $assignment->instance;
500 $assignment->courseid = $assignment->course;
502 $DB->update_record('assignment', $assignment);
504 if ($assignment->timedue) {
505 $event = new object();
507 if ($event->id = $DB->get_field('event', 'id', array('modulename'=>'assignment', 'instance'=>$assignment->id))) {
509 $event->name = $assignment->name;
510 $event->description = format_module_intro('assignment', $assignment, $assignment->coursemodule);
511 $event->timestart = $assignment->timedue;
513 $calendarevent = calendar_event::load($event->id);
514 $calendarevent->update($event);
516 $event = new object();
517 $event->name = $assignment->name;
518 $event->description = format_module_intro('assignment', $assignment, $assignment->coursemodule);
519 $event->courseid = $assignment->course;
522 $event->modulename = 'assignment';
523 $event->instance = $assignment->id;
524 $event->eventtype = 'due';
525 $event->timestart = $assignment->timedue;
526 $event->timeduration = 0;
528 calendar_event::create($event);
531 $DB->delete_records('event', array('modulename'=>'assignment', 'instance'=>$assignment->id));
534 // get existing grade item
535 assignment_grade_item_update($assignment);
541 * Update grade item for this submission.
543 function update_grade($submission) {
544 assignment_update_grades($this->assignment, $submission->userid);
548 * Top-level function for handling of submissions called by submissions.php
550 * This is for handling the teacher interaction with the grading interface
551 * This should be suitable for most assignment types.
554 * @param string $mode Specifies the kind of teacher interaction taking place
556 function submissions($mode) {
557 ///The main switch is changed to facilitate
558 ///1) Batch fast grading
559 ///2) Skip to the next one on the popup
560 ///3) Save and Skip to the next one on the popup
562 //make user global so we can use the id
563 global $USER, $OUTPUT, $DB, $PAGE;
565 $mailinfo = optional_param('mailinfo', null, PARAM_BOOL);
566 $saved = optional_param('saved', null, PARAM_BOOL);
568 if (optional_param('next', null, PARAM_BOOL)) {
571 if (optional_param('saveandnext', null, PARAM_BOOL)) {
575 if (is_null($mailinfo)) {
576 $mailinfo = get_user_preferences('assignment_mailinfo', 0);
578 set_user_preference('assignment_mailinfo', $mailinfo);
582 $OUTPUT->heading(get_string('changessaved'));
586 case 'grade': // We are in a main window grading
587 if ($submission = $this->process_feedback()) {
588 $this->display_submissions(get_string('changessaved'));
590 $this->display_submissions();
594 case 'single': // We are in a main window displaying one submission
595 if ($submission = $this->process_feedback()) {
596 $this->display_submissions(get_string('changessaved'));
598 $this->display_submission();
602 case 'all': // Main window, display everything
603 $this->display_submissions();
607 ///do the fast grading stuff - this process should work for all 3 subclasses
611 if (isset($_POST['submissioncomment'])) {
612 $col = 'submissioncomment';
615 if (isset($_POST['menu'])) {
620 //both submissioncomment and grade columns collapsed..
621 $this->display_submissions();
625 foreach ($_POST[$col] as $id => $unusedvalue){
627 $id = (int)$id; //clean parameter name
629 $this->process_outcomes($id);
631 if (!$submission = $this->get_submission($id)) {
632 $submission = $this->prepare_new_submission($id);
633 $newsubmission = true;
635 $newsubmission = false;
637 unset($submission->data1); // Don't need to update this.
638 unset($submission->data2); // Don't need to update this.
640 //for fast grade, we need to check if any changes take place
644 $grade = $_POST['menu'][$id];
645 $updatedb = $updatedb || ($submission->grade != $grade);
646 $submission->grade = $grade;
648 if (!$newsubmission) {
649 unset($submission->grade); // Don't need to update this.
653 $commentvalue = trim($_POST['submissioncomment'][$id]);
654 $updatedb = $updatedb || ($submission->submissioncomment != $commentvalue);
655 $submission->submissioncomment = $commentvalue;
657 unset($submission->submissioncomment); // Don't need to update this.
660 $submission->teacher = $USER->id;
662 $submission->mailed = (int)(!$mailinfo);
665 $submission->timemarked = time();
667 //if it is not an update, we don't change the last modified time etc.
668 //this will also not write into database if no submissioncomment and grade is entered.
671 if ($newsubmission) {
672 if (!isset($submission->submissioncomment)) {
673 $submission->submissioncomment = '';
675 $sid = $DB->insert_record('assignment_submissions', $submission);
676 $submission->id = $sid;
678 $DB->update_record('assignment_submissions', $submission);
681 // triger grade event
682 $this->update_grade($submission);
684 //add to log only if updating
685 add_to_log($this->course->id, 'assignment', 'update grades',
686 'submissions.php?id='.$this->assignment->id.'&user='.$submission->userid,
687 $submission->userid, $this->cm->id);
692 $message = $OUTPUT->notification(get_string('changessaved'), 'notifysuccess');
694 $this->display_submissions($message);
699 ///We are in pop up. save the current one and go to the next one.
700 //first we save the current changes
701 if ($submission = $this->process_feedback()) {
702 //print_heading(get_string('changessaved'));
703 //$extra_javascript = $this->update_main_listing($submission);
707 /// We are currently in pop up, but we want to skip to next one without saving.
708 /// This turns out to be similar to a single case
709 /// The URL used is for the next submission.
710 $offset = required_param('offset', PARAM_INT);
711 $nextid = required_param('nextid', PARAM_INT);
712 $id = required_param('id', PARAM_INT);
713 $offset = (int)$offset+1;
714 //$this->display_submission($offset+1 , $nextid);
715 redirect('submissions.php?id='.$id.'&userid='. $nextid . '&mode=single&offset='.$offset);
719 echo "something seriously is wrong!!";
725 * Helper method updating the listing on the main script from popup using javascript
729 * @param $submission object The submission whose data is to be updated on the main page
731 function update_main_listing($submission) {
732 global $SESSION, $CFG, $OUTPUT;
736 $perpage = get_user_preferences('assignment_perpage', 10);
738 $quickgrade = get_user_preferences('assignment_quickgrade', 0);
740 /// Run some Javascript to try and update the parent page
741 $output .= '<script type="text/javascript">'."\n<!--\n";
742 if (empty($SESSION->flextable['mod-assignment-submissions']->collapse['submissioncomment'])) {
744 $output.= 'opener.document.getElementById("submissioncomment'.$submission->userid.'").value="'
745 .trim($submission->submissioncomment).'";'."\n";
747 $output.= 'opener.document.getElementById("com'.$submission->userid.
748 '").innerHTML="'.shorten_text(trim(strip_tags($submission->submissioncomment)), 15)."\";\n";
752 if (empty($SESSION->flextable['mod-assignment-submissions']->collapse['grade'])) {
753 //echo optional_param('menuindex');
755 $output.= 'opener.document.getElementById("menumenu'.$submission->userid.
756 '").selectedIndex="'.optional_param('menuindex', 0, PARAM_INT).'";'."\n";
758 $output.= 'opener.document.getElementById("g'.$submission->userid.'").innerHTML="'.
759 $this->display_grade($submission->grade)."\";\n";
762 //need to add student's assignments in there too.
763 if (empty($SESSION->flextable['mod-assignment-submissions']->collapse['timemodified']) &&
764 $submission->timemodified) {
765 $output.= 'opener.document.getElementById("ts'.$submission->userid.
766 '").innerHTML="'.addslashes_js($this->print_student_answer($submission->userid)).userdate($submission->timemodified)."\";\n";
769 if (empty($SESSION->flextable['mod-assignment-submissions']->collapse['timemarked']) &&
770 $submission->timemarked) {
771 $output.= 'opener.document.getElementById("tt'.$submission->userid.
772 '").innerHTML="'.userdate($submission->timemarked)."\";\n";
775 if (empty($SESSION->flextable['mod-assignment-submissions']->collapse['status'])) {
776 $output.= 'opener.document.getElementById("up'.$submission->userid.'").className="s1";';
777 $buttontext = get_string('update');
778 $url = new moodle_url('/mod/assignment/submissions.php', array(
779 'id' => $this->cm->id,
780 'userid' => $submission->userid,
782 'offset' => (optional_param('offset', '', PARAM_INT)-1)));
783 $button = $OUTPUT->action_link($url, $buttontext, new popup_action('click', $url, 'grade'.$submission->userid, array('height' => 450, 'width' => 700)), array('ttile'=>$buttontext));
785 $output .= 'opener.document.getElementById("up'.$submission->userid.'").innerHTML="'.addslashes_js($button).'";';
788 $grading_info = grade_get_grades($this->course->id, 'mod', 'assignment', $this->assignment->id, $submission->userid);
790 if (empty($SESSION->flextable['mod-assignment-submissions']->collapse['finalgrade'])) {
791 $output.= 'opener.document.getElementById("finalgrade_'.$submission->userid.
792 '").innerHTML="'.$grading_info->items[0]->grades[$submission->userid]->str_grade.'";'."\n";
795 if (!empty($CFG->enableoutcomes) and empty($SESSION->flextable['mod-assignment-submissions']->collapse['outcome'])) {
797 if (!empty($grading_info->outcomes)) {
798 foreach($grading_info->outcomes as $n=>$outcome) {
799 if ($outcome->grades[$submission->userid]->locked) {
804 $output.= 'opener.document.getElementById("outcome_'.$n.'_'.$submission->userid.
805 '").selectedIndex="'.$outcome->grades[$submission->userid]->grade.'";'."\n";
808 $options = make_grades_menu(-$outcome->scaleid);
809 $options[0] = get_string('nooutcome', 'grades');
810 $output.= 'opener.document.getElementById("outcome_'.$n.'_'.$submission->userid.'").innerHTML="'.$options[$outcome->grades[$submission->userid]->grade]."\";\n";
817 $output .= "\n-->\n</script>";
822 * Return a grade in user-friendly form, whether it's a scale or not
825 * @param mixed $grade
826 * @return string User-friendly representation of grade
828 function display_grade($grade) {
831 static $scalegrades = array(); // Cache scales for each assignment - they might have different scales!!
833 if ($this->assignment->grade >= 0) { // Normal number
837 return $grade.' / '.$this->assignment->grade;
841 if (empty($scalegrades[$this->assignment->id])) {
842 if ($scale = $DB->get_record('scale', array('id'=>-($this->assignment->grade)))) {
843 $scalegrades[$this->assignment->id] = make_menu_from_list($scale->scale);
848 if (isset($scalegrades[$this->assignment->id][$grade])) {
849 return $scalegrades[$this->assignment->id][$grade];
856 * Display a single submission, ready for grading on a popup window
858 * This default method prints the teacher info and submissioncomment box at the top and
859 * the student info and submission at the bottom.
860 * This method also fetches the necessary data in order to be able to
861 * provide a "Next submission" button.
862 * Calls preprocess_submission() to give assignment type plug-ins a chance
863 * to process submissions before they are graded
864 * This method gets its arguments from the page parameters userid and offset
868 * @param string $extra_javascript
870 function display_submission($offset=-1,$userid =-1) {
871 global $CFG, $DB, $PAGE, $OUTPUT;
872 require_once($CFG->libdir.'/gradelib.php');
873 require_once($CFG->libdir.'/tablelib.php');
875 $userid = required_param('userid', PARAM_INT);
878 $offset = required_param('offset', PARAM_INT);//offset for where to start looking for student.
881 if (!$user = $DB->get_record('user', array('id'=>$userid))) {
882 print_error('nousers');
885 if (!$submission = $this->get_submission($user->id)) {
886 $submission = $this->prepare_new_submission($userid);
888 if ($submission->timemodified > $submission->timemarked) {
889 $subtype = 'assignmentnew';
891 $subtype = 'assignmentold';
894 $grading_info = grade_get_grades($this->course->id, 'mod', 'assignment', $this->assignment->id, array($user->id));
895 $gradingdisabled = $grading_info->items[0]->grades[$userid]->locked || $grading_info->items[0]->grades[$userid]->overridden;
897 /// construct SQL, using current offset to find the data of the next student
898 $course = $this->course;
899 $assignment = $this->assignment;
901 $context = get_context_instance(CONTEXT_MODULE, $cm->id);
903 /// Get all ppl that can submit assignments
905 $currentgroup = groups_get_activity_group($cm);
906 if ($users = get_enrolled_users($context, 'mod/assignment:submit', $currentgroup, 'u.id')) {
907 $users = array_keys($users);
910 // if groupmembersonly used, remove users who are not in any group
911 if ($users and !empty($CFG->enablegroupmembersonly) and $cm->groupmembersonly) {
912 if ($groupingusers = groups_get_grouping_members($cm->groupingid, 'u.id', 'u.id')) {
913 $users = array_intersect($users, array_keys($groupingusers));
920 $userfields = user_picture::fields('u', array('lastaccess'));
921 $select = "SELECT $userfields,
922 s.id AS submissionid, s.grade, s.submissioncomment,
923 s.timemodified, s.timemarked,
924 COALESCE(SIGN(SIGN(s.timemarked) + SIGN(s.timemarked - s.timemodified)), 0) AS status ";
925 $sql = 'FROM {user} u '.
926 'LEFT JOIN {assignment_submissions} s ON u.id = s.userid
927 AND s.assignment = '.$this->assignment->id.' '.
928 'WHERE u.id IN ('.implode(',', $users).') ';
930 if ($sort = flexible_table::get_sort_for_table('mod-assignment-submissions')) {
931 $sort = 'ORDER BY '.$sort.' ';
933 $auser = $DB->get_records_sql($select.$sql.$sort, null, $offset, 2);
935 if (is_array($auser) && count($auser)>1) {
936 $nextuser = next($auser);
937 /// Calculate user status
938 $nextuser->status = ($nextuser->timemarked > 0) && ($nextuser->timemarked >= $nextuser->timemodified);
939 $nextid = $nextuser->id;
943 if ($submission->teacher) {
944 $teacher = $DB->get_record('user', array('id'=>$submission->teacher));
950 $this->preprocess_submission($submission);
952 $mformdata = new stdclass;
953 $mformdata->context = $this->context;
954 $mformdata->maxbytes = $this->course->maxbytes;
955 $mformdata->courseid = $this->course->id;
956 $mformdata->teacher = $teacher;
957 $mformdata->assignment = $assignment;
958 $mformdata->submission = $submission;
959 $mformdata->lateness = $this->display_lateness($submission->timemodified);
960 $mformdata->auser = $auser;
961 $mformdata->user = $user;
962 $mformdata->offset = $offset;
963 $mformdata->userid = $userid;
964 $mformdata->cm = $this->cm;
965 $mformdata->grading_info = $grading_info;
966 $mformdata->enableoutcomes = $CFG->enableoutcomes;
967 $mformdata->grade = $this->assignment->grade;
968 $mformdata->gradingdisabled = $gradingdisabled;
969 $mformdata->usehtmleditor = $this->usehtmleditor;
970 $mformdata->nextid = $nextid;
971 $mformdata->submissioncomment= $submission->submissioncomment;
972 $mformdata->submissioncommentformat= FORMAT_HTML;
973 $mformdata->submission_content= $this->print_user_files($user->id, true);
975 $submitform = new mod_assignment_online_grading_form( null, $mformdata );
977 if ($submitform->is_cancelled()) {
978 redirect('submissions.php?id='.$this->cm->id);
981 $submitform->set_data($mformdata);
983 $PAGE->set_title($this->course->fullname . ': ' .get_string('feedback', 'assignment').' - '.fullname($user, true));
984 $PAGE->set_heading($this->course->fullname);
985 $PAGE->navbar->add( get_string('submissions', 'assignment') );
987 echo $OUTPUT->header();
988 echo $OUTPUT->heading(get_string('feedback', 'assignment').': '.fullname($user, true));
990 // display mform here...
991 $submitform->display();
993 $customfeedback = $this->custom_feedbackform($submission, true);
994 if (!empty($customfeedback)) {
995 echo $customfeedback;
998 echo $OUTPUT->footer();
1002 * Preprocess submission before grading
1004 * Called by display_submission()
1005 * The default type does nothing here.
1007 * @param object $submission The submission object
1009 function preprocess_submission(&$submission) {
1013 * Display all the submissions ready for grading
1019 * @param string $message
1022 function display_submissions($message='') {
1023 global $CFG, $DB, $USER, $DB, $OUTPUT, $PAGE;
1024 require_once($CFG->libdir.'/gradelib.php');
1026 /* first we check to see if the form has just been submitted
1027 * to request user_preference updates
1029 if (isset($_POST['updatepref'])){
1030 $perpage = optional_param('perpage', 10, PARAM_INT);
1031 $perpage = ($perpage <= 0) ? 10 : $perpage ;
1032 set_user_preference('assignment_perpage', $perpage);
1033 set_user_preference('assignment_quickgrade', optional_param('quickgrade', 0, PARAM_BOOL));
1036 /* next we get perpage and quickgrade (allow quick grade) params
1039 $perpage = get_user_preferences('assignment_perpage', 10);
1041 $quickgrade = get_user_preferences('assignment_quickgrade', 0);
1043 $grading_info = grade_get_grades($this->course->id, 'mod', 'assignment', $this->assignment->id);
1045 if (!empty($CFG->enableoutcomes) and !empty($grading_info->outcomes)) {
1046 $uses_outcomes = true;
1048 $uses_outcomes = false;
1051 $page = optional_param('page', 0, PARAM_INT);
1052 $strsaveallfeedback = get_string('saveallfeedback', 'assignment');
1054 /// Some shortcuts to make the code read better
1056 $course = $this->course;
1057 $assignment = $this->assignment;
1060 $tabindex = 1; //tabindex for quick grading tabbing; Not working for dropdowns yet
1061 add_to_log($course->id, 'assignment', 'view submission', 'submissions.php?id='.$this->cm->id, $this->assignment->id, $this->cm->id);
1063 $PAGE->set_title(format_string($this->assignment->name,true));
1064 $PAGE->set_heading($this->course->fullname);
1065 echo $OUTPUT->header();
1067 /// Print quickgrade form around the table
1069 echo '<form action="submissions.php" id="fastg" method="post">';
1071 echo '<input type="hidden" name="id" value="'.$this->cm->id.'" />';
1072 echo '<input type="hidden" name="mode" value="fastgrade" />';
1073 echo '<input type="hidden" name="page" value="'.$page.'" />';
1074 echo '<input type="hidden" name="sesskey" value="'.sesskey().'" />';
1078 $course_context = get_context_instance(CONTEXT_COURSE, $course->id);
1079 if (has_capability('gradereport/grader:view', $course_context) && has_capability('moodle/grade:viewall', $course_context)) {
1080 echo '<div class="allcoursegrades"><a href="' . $CFG->wwwroot . '/grade/report/grader/index.php?id=' . $course->id . '">'
1081 . get_string('seeallcoursegrades', 'grades') . '</a></div>';
1084 if (!empty($message)) {
1085 echo $message; // display messages here if any
1088 $context = get_context_instance(CONTEXT_MODULE, $cm->id);
1090 /// Check to see if groups are being used in this assignment
1092 /// find out current groups mode
1093 $groupmode = groups_get_activity_groupmode($cm);
1094 $currentgroup = groups_get_activity_group($cm, true);
1095 groups_print_activity_menu($cm, $CFG->wwwroot . '/mod/assignment/submissions.php?id=' . $this->cm->id);
1097 /// Get all ppl that are allowed to submit assignments
1098 if ($users = get_enrolled_users($context, 'mod/assignment:submit', $currentgroup, 'u.id')) {
1099 $users = array_keys($users);
1102 // if groupmembersonly used, remove users who are not in any group
1103 if ($users and !empty($CFG->enablegroupmembersonly) and $cm->groupmembersonly) {
1104 if ($groupingusers = groups_get_grouping_members($cm->groupingid, 'u.id', 'u.id')) {
1105 $users = array_intersect($users, array_keys($groupingusers));
1109 $tablecolumns = array('picture', 'fullname', 'grade', 'submissioncomment', 'timemodified', 'timemarked', 'status', 'finalgrade');
1110 if ($uses_outcomes) {
1111 $tablecolumns[] = 'outcome'; // no sorting based on outcomes column
1114 $tableheaders = array('',
1115 get_string('fullname'),
1116 get_string('grade'),
1117 get_string('comment', 'assignment'),
1118 get_string('lastmodified').' ('.get_string('submission', 'assignment').')',
1119 get_string('lastmodified').' ('.get_string('grade').')',
1120 get_string('status'),
1121 get_string('finalgrade', 'grades'));
1122 if ($uses_outcomes) {
1123 $tableheaders[] = get_string('outcome', 'grades');
1126 require_once($CFG->libdir.'/tablelib.php');
1127 $table = new flexible_table('mod-assignment-submissions');
1129 $table->define_columns($tablecolumns);
1130 $table->define_headers($tableheaders);
1131 $table->define_baseurl($CFG->wwwroot.'/mod/assignment/submissions.php?id='.$this->cm->id.'&currentgroup='.$currentgroup);
1133 $table->sortable(true, 'lastname');//sorted by lastname by default
1134 $table->collapsible(true);
1135 $table->initialbars(true);
1137 $table->column_suppress('picture');
1138 $table->column_suppress('fullname');
1140 $table->column_class('picture', 'picture');
1141 $table->column_class('fullname', 'fullname');
1142 $table->column_class('grade', 'grade');
1143 $table->column_class('submissioncomment', 'comment');
1144 $table->column_class('timemodified', 'timemodified');
1145 $table->column_class('timemarked', 'timemarked');
1146 $table->column_class('status', 'status');
1147 $table->column_class('finalgrade', 'finalgrade');
1148 if ($uses_outcomes) {
1149 $table->column_class('outcome', 'outcome');
1152 $table->set_attribute('cellspacing', '0');
1153 $table->set_attribute('id', 'attempts');
1154 $table->set_attribute('class', 'submissions');
1155 $table->set_attribute('width', '100%');
1156 //$table->set_attribute('align', 'center');
1158 $table->no_sorting('finalgrade');
1159 $table->no_sorting('outcome');
1161 // Start working -- this is necessary as soon as the niceties are over
1164 if (empty($users)) {
1165 echo $OUTPUT->heading(get_string('nosubmitusers','assignment'));
1169 if ($this->assignment->assignmenttype=='upload' || $this->assignment->assignmenttype=='online' || $this->assignment->assignmenttype=='uploadsingle') { //TODO: this is an ugly hack, where is the plugin spirit? (skodak)
1170 echo '<div style="text-align:right"><a href="submissions.php?id='.$this->cm->id.'&download=zip">'.get_string('downloadall', 'assignment').'</a></div>';
1172 /// Construct the SQL
1174 if ($where = $table->get_sql_where()) {
1178 if ($sort = $table->get_sql_sort()) {
1179 $sort = ' ORDER BY '.$sort;
1182 $ufields = user_picture::fields('u');
1183 $select = "SELECT $ufields,
1184 s.id AS submissionid, s.grade, s.submissioncomment,
1185 s.timemodified, s.timemarked,
1186 COALESCE(SIGN(SIGN(s.timemarked) + SIGN(s.timemarked - s.timemodified)), 0) AS status ";
1187 $sql = 'FROM {user} u '.
1188 'LEFT JOIN {assignment_submissions} s ON u.id = s.userid
1189 AND s.assignment = '.$this->assignment->id.' '.
1190 'WHERE '.$where.'u.id IN ('.implode(',',$users).') ';
1192 $table->pagesize($perpage, count($users));
1194 ///offset used to calculate index of student in that particular query, needed for the pop up to know who's next
1195 $offset = $page * $perpage;
1197 $strupdate = get_string('update');
1198 $strgrade = get_string('grade');
1199 $grademenu = make_grades_menu($this->assignment->grade);
1201 if (($ausers = $DB->get_records_sql($select.$sql.$sort, null, $table->get_page_start(), $table->get_page_size())) !== false) {
1202 $grading_info = grade_get_grades($this->course->id, 'mod', 'assignment', $this->assignment->id, array_keys($ausers));
1203 foreach ($ausers as $auser) {
1204 $final_grade = $grading_info->items[0]->grades[$auser->id];
1205 $grademax = $grading_info->items[0]->grademax;
1206 $final_grade->formatted_grade = round($final_grade->grade,2) .' / ' . round($grademax,2);
1207 $locked_overridden = 'locked';
1208 if ($final_grade->overridden) {
1209 $locked_overridden = 'overridden';
1212 /// Calculate user status
1213 $auser->status = ($auser->timemarked > 0) && ($auser->timemarked >= $auser->timemodified);
1214 $picture = $OUTPUT->user_picture($auser);
1216 if (empty($auser->submissionid)) {
1217 $auser->grade = -1; //no submission yet
1220 if (!empty($auser->submissionid)) {
1221 ///Prints student answer and student modified date
1222 ///attach file or print link to student answer, depending on the type of the assignment.
1223 ///Refer to print_student_answer in inherited classes.
1224 if ($auser->timemodified > 0) {
1225 $studentmodified = '<div id="ts'.$auser->id.'">'.$this->print_student_answer($auser->id)
1226 . userdate($auser->timemodified).'</div>';
1228 $studentmodified = '<div id="ts'.$auser->id.'"> </div>';
1230 ///Print grade, dropdown or text
1231 if ($auser->timemarked > 0) {
1232 $teachermodified = '<div id="tt'.$auser->id.'">'.userdate($auser->timemarked).'</div>';
1234 if ($final_grade->locked or $final_grade->overridden) {
1235 $grade = '<div id="g'.$auser->id.'" class="'. $locked_overridden .'">'.$final_grade->formatted_grade.'</div>';
1236 } else if ($quickgrade) {
1237 $attributes = array();
1238 $attributes['tabindex'] = $tabindex++;
1239 $menu = html_writer::select(make_grades_menu($this->assignment->grade), 'menu['.$auser->id.']', $auser->grade, array(-1=>get_string('nograde')), $attributes);
1240 $grade = '<div id="g'.$auser->id.'">'. $menu .'</div>';
1242 $grade = '<div id="g'.$auser->id.'">'.$this->display_grade($auser->grade).'</div>';
1246 $teachermodified = '<div id="tt'.$auser->id.'"> </div>';
1247 if ($final_grade->locked or $final_grade->overridden) {
1248 $grade = '<div id="g'.$auser->id.'" class="'. $locked_overridden .'">'.$final_grade->formatted_grade.'</div>';
1249 } else if ($quickgrade) {
1250 $attributes = array();
1251 $attributes['tabindex'] = $tabindex++;
1252 $menu = html_writer::select(make_grades_menu($this->assignment->grade), 'menu['.$auser->id.']', $auser->grade, array(-1=>get_string('nograde')), $attributes);
1253 $grade = '<div id="g'.$auser->id.'">'.$menu.'</div>';
1255 $grade = '<div id="g'.$auser->id.'">'.$this->display_grade($auser->grade).'</div>';
1259 if ($final_grade->locked or $final_grade->overridden) {
1260 $comment = '<div id="com'.$auser->id.'">'.shorten_text(strip_tags($final_grade->str_feedback),15).'</div>';
1262 } else if ($quickgrade) {
1263 $comment = '<div id="com'.$auser->id.'">'
1264 . '<textarea tabindex="'.$tabindex++.'" name="submissioncomment['.$auser->id.']" id="submissioncomment'
1265 . $auser->id.'" rows="2" cols="20">'.($auser->submissioncomment).'</textarea></div>';
1267 $comment = '<div id="com'.$auser->id.'">'.shorten_text(strip_tags($auser->submissioncomment),15).'</div>';
1270 $studentmodified = '<div id="ts'.$auser->id.'"> </div>';
1271 $teachermodified = '<div id="tt'.$auser->id.'"> </div>';
1272 $status = '<div id="st'.$auser->id.'"> </div>';
1274 if ($final_grade->locked or $final_grade->overridden) {
1275 $grade = '<div id="g'.$auser->id.'">'.$final_grade->formatted_grade . '</div>';
1276 } else if ($quickgrade) { // allow editing
1277 $attributes = array();
1278 $attributes['tabindex'] = $tabindex++;
1279 $menu = html_writer::select(make_grades_menu($this->assignment->grade), 'menu['.$auser->id.']', $auser->grade, array(-1=>get_string('nograde')), $attributes);
1280 $grade = '<div id="g'.$auser->id.'">'.$menu.'</div>';
1282 $grade = '<div id="g'.$auser->id.'">-</div>';
1285 if ($final_grade->locked or $final_grade->overridden) {
1286 $comment = '<div id="com'.$auser->id.'">'.$final_grade->str_feedback.'</div>';
1287 } else if ($quickgrade) {
1288 $comment = '<div id="com'.$auser->id.'">'
1289 . '<textarea tabindex="'.$tabindex++.'" name="submissioncomment['.$auser->id.']" id="submissioncomment'
1290 . $auser->id.'" rows="2" cols="20">'.($auser->submissioncomment).'</textarea></div>';
1292 $comment = '<div id="com'.$auser->id.'"> </div>';
1296 if (empty($auser->status)) { /// Confirm we have exclusively 0 or 1
1302 $buttontext = ($auser->status == 1) ? $strupdate : $strgrade;
1304 ///No more buttons, we use popups ;-).
1305 $popup_url = '/mod/assignment/submissions.php?id='.$this->cm->id
1306 . '&userid='.$auser->id.'&mode=single'.'&offset='.$offset++;
1308 $button = $OUTPUT->action_link($popup_url, $buttontext);
1310 $status = '<div id="up'.$auser->id.'" class="s'.$auser->status.'">'.$button.'</div>';
1312 $finalgrade = '<span id="finalgrade_'.$auser->id.'">'.$final_grade->str_grade.'</span>';
1316 if ($uses_outcomes) {
1318 foreach($grading_info->outcomes as $n=>$outcome) {
1319 $outcomes .= '<div class="outcome"><label>'.$outcome->name.'</label>';
1320 $options = make_grades_menu(-$outcome->scaleid);
1322 if ($outcome->grades[$auser->id]->locked or !$quickgrade) {
1323 $options[0] = get_string('nooutcome', 'grades');
1324 $outcomes .= ': <span id="outcome_'.$n.'_'.$auser->id.'">'.$options[$outcome->grades[$auser->id]->grade].'</span>';
1326 $attributes = array();
1327 $attributes['tabindex'] = $tabindex++;
1328 $attributes['id'] = 'outcome_'.$n.'_'.$auser->id;
1329 $outcomes .= ' '.html_writer::select($options, 'outcome_'.$n.'['.$auser->id.']', $outcome->grades[$auser->id]->grade, array(0=>get_string('nooutcome', 'grades')), $attributes);
1331 $outcomes .= '</div>';
1335 $userlink = '<a href="' . $CFG->wwwroot . '/user/view.php?id=' . $auser->id . '&course=' . $course->id . '">' . fullname($auser) . '</a>';
1336 $row = array($picture, $userlink, $grade, $comment, $studentmodified, $teachermodified, $status, $finalgrade);
1337 if ($uses_outcomes) {
1341 $table->add_data($row);
1345 $table->print_html(); /// Print the whole table
1348 $lastmailinfo = get_user_preferences('assignment_mailinfo', 1) ? 'checked="checked"' : '';
1349 echo '<div class="fgcontrols">';
1350 echo '<div class="emailnotification">';
1351 echo '<label for="mailinfo">'.get_string('enableemailnotification','assignment').'</label>';
1352 echo '<input type="hidden" name="mailinfo" value="0" />';
1353 echo '<input type="checkbox" id="mailinfo" name="mailinfo" value="1" '.$lastmailinfo.' />';
1354 echo $OUTPUT->help_icon('enableemailnotification', 'assignment');
1357 echo '<div class="fastgbutton"><input type="submit" name="fastg" value="'.get_string('saveallfeedback', 'assignment').'" /></div>';
1360 /// End of fast grading form
1362 /// Mini form for setting user preference
1363 echo '<div class="qgprefs">';
1364 echo '<form id="options" action="submissions.php?id='.$this->cm->id.'" method="post"><div>';
1365 echo '<input type="hidden" name="updatepref" value="1" />';
1366 echo '<table id="optiontable">';
1368 echo '<label for="perpage">'.get_string('pagesize','assignment').'</label>';
1371 echo '<input type="text" id="perpage" name="perpage" size="1" value="'.$perpage.'" />';
1374 echo '<label for="quickgrade">'.get_string('quickgrade','assignment').'</label>';
1377 $checked = $quickgrade ? 'checked="checked"' : '';
1378 echo '<input type="checkbox" id="quickgrade" name="quickgrade" value="1" '.$checked.' />';
1379 echo '<p>'.$OUTPUT->help_icon('quickgrade', 'assignment').'</p>';
1382 echo '<tr><td colspan="2">';
1383 echo '<input type="submit" value="'.get_string('savepreferences').'" />';
1384 echo '</td></tr></table>';
1385 echo '</div></form></div>';
1387 echo $OUTPUT->footer();
1391 * Process teacher feedback submission
1393 * This is called by submissions() when a grading even has taken place.
1394 * It gets its data from the submitted form.
1399 * @return object|bool The updated submission object or false
1401 function process_feedback() {
1402 global $CFG, $USER, $DB;
1403 require_once($CFG->libdir.'/gradelib.php');
1405 if (!$feedback = data_submitted() or !confirm_sesskey()) { // No incoming data?
1409 ///For save and next, we need to know the userid to save, and the userid to go
1410 ///We use a new hidden field in the form, and set it to -1. If it's set, we use this
1411 ///as the userid to store
1412 if ((int)$feedback->saveuserid !== -1){
1413 $feedback->userid = $feedback->saveuserid;
1416 if (!empty($feedback->cancel)) { // User hit cancel button
1420 $grading_info = grade_get_grades($this->course->id, 'mod', 'assignment', $this->assignment->id, $feedback->userid);
1422 // store outcomes if needed
1423 $this->process_outcomes($feedback->userid);
1425 $submission = $this->get_submission($feedback->userid, true); // Get or make one
1427 if (!($grading_info->items[0]->grades[$feedback->userid]->locked ||
1428 $grading_info->items[0]->grades[$feedback->userid]->overridden) ) {
1430 $submission->grade = $feedback->xgrade;
1431 $submission->submissioncomment = $feedback->submissioncomment_editor['text'];
1432 $submission->format = $feedback->format;
1433 $submission->teacher = $USER->id;
1434 $mailinfo = get_user_preferences('assignment_mailinfo', 0);
1436 $submission->mailed = 1; // treat as already mailed
1438 $submission->mailed = 0; // Make sure mail goes out (again, even)
1440 $submission->timemarked = time();
1442 unset($submission->data1); // Don't need to update this.
1443 unset($submission->data2); // Don't need to update this.
1445 if (empty($submission->timemodified)) { // eg for offline assignments
1446 // $submission->timemodified = time();
1449 $DB->update_record('assignment_submissions', $submission);
1451 // triger grade event
1452 $this->update_grade($submission);
1454 add_to_log($this->course->id, 'assignment', 'update grades',
1455 'submissions.php?id='.$this->assignment->id.'&user='.$feedback->userid, $feedback->userid, $this->cm->id);
1462 function process_outcomes($userid) {
1465 if (empty($CFG->enableoutcomes)) {
1469 require_once($CFG->libdir.'/gradelib.php');
1471 if (!$formdata = data_submitted() or !confirm_sesskey()) {
1476 $grading_info = grade_get_grades($this->course->id, 'mod', 'assignment', $this->assignment->id, $userid);
1478 if (!empty($grading_info->outcomes)) {
1479 foreach($grading_info->outcomes as $n=>$old) {
1480 $name = 'outcome_'.$n;
1481 if (isset($formdata->{$name}[$userid]) and $old->grades[$userid]->grade != $formdata->{$name}[$userid]) {
1482 $data[$n] = $formdata->{$name}[$userid];
1486 if (count($data) > 0) {
1487 grade_update_outcomes('mod/assignment', $this->course->id, 'mod', 'assignment', $this->assignment->id, $userid, $data);
1493 * Load the submission object for a particular user
1497 * @param $userid int The id of the user whose submission we want or 0 in which case USER->id is used
1498 * @param $createnew boolean optional Defaults to false. If set to true a new submission object will be created in the database
1499 * @param bool $teachermodified student submission set if false
1500 * @return object The submission
1502 function get_submission($userid=0, $createnew=false, $teachermodified=false) {
1505 if (empty($userid)) {
1506 $userid = $USER->id;
1509 $submission = $DB->get_record('assignment_submissions', array('assignment'=>$this->assignment->id, 'userid'=>$userid));
1511 if ($submission || !$createnew) {
1514 $newsubmission = $this->prepare_new_submission($userid, $teachermodified);
1515 $DB->insert_record("assignment_submissions", $newsubmission);
1517 return $DB->get_record('assignment_submissions', array('assignment'=>$this->assignment->id, 'userid'=>$userid));
1521 * Instantiates a new submission object for a given user
1523 * Sets the assignment, userid and times, everything else is set to default values.
1525 * @param int $userid The userid for which we want a submission object
1526 * @param bool $teachermodified student submission set if false
1527 * @return object The submission
1529 function prepare_new_submission($userid, $teachermodified=false) {
1530 $submission = new Object;
1531 $submission->assignment = $this->assignment->id;
1532 $submission->userid = $userid;
1533 $submission->timecreated = time();
1534 // teachers should not be modifying modified date, except offline assignments
1535 if ($teachermodified) {
1536 $submission->timemodified = 0;
1538 $submission->timemodified = $submission->timecreated;
1540 $submission->numfiles = 0;
1541 $submission->data1 = '';
1542 $submission->data2 = '';
1543 $submission->grade = -1;
1544 $submission->submissioncomment = '';
1545 $submission->format = 0;
1546 $submission->teacher = 0;
1547 $submission->timemarked = 0;
1548 $submission->mailed = 0;
1553 * Return all assignment submissions by ENROLLED students (even empty)
1555 * @param string $sort optional field names for the ORDER BY in the sql query
1556 * @param string $dir optional specifying the sort direction, defaults to DESC
1557 * @return array The submission objects indexed by id
1559 function get_submissions($sort='', $dir='DESC') {
1560 return assignment_get_all_submissions($this->assignment, $sort, $dir);
1564 * Counts all real assignment submissions by ENROLLED students (not empty ones)
1566 * @param int $groupid optional If nonzero then count is restricted to this group
1567 * @return int The number of submissions
1569 function count_real_submissions($groupid=0) {
1570 return assignment_count_real_submissions($this->cm, $groupid);
1574 * Alerts teachers by email of new or changed assignments that need grading
1576 * First checks whether the option to email teachers is set for this assignment.
1577 * Sends an email to ALL teachers in the course (or in the group if using separate groups).
1578 * Uses the methods email_teachers_text() and email_teachers_html() to construct the content.
1582 * @param $submission object The submission that has changed
1585 function email_teachers($submission) {
1588 if (empty($this->assignment->emailteachers)) { // No need to do anything
1592 $user = $DB->get_record('user', array('id'=>$submission->userid));
1594 if ($teachers = $this->get_graders($user)) {
1596 $strassignments = get_string('modulenameplural', 'assignment');
1597 $strassignment = get_string('modulename', 'assignment');
1598 $strsubmitted = get_string('submitted', 'assignment');
1600 foreach ($teachers as $teacher) {
1601 $info = new object();
1602 $info->username = fullname($user, true);
1603 $info->assignment = format_string($this->assignment->name,true);
1604 $info->url = $CFG->wwwroot.'/mod/assignment/submissions.php?id='.$this->cm->id;
1606 $postsubject = $strsubmitted.': '.$info->username.' -> '.$this->assignment->name;
1607 $posttext = $this->email_teachers_text($info);
1608 $posthtml = ($teacher->mailformat == 1) ? $this->email_teachers_html($info) : '';
1610 $eventdata = new object();
1611 $eventdata->modulename = 'assignment';
1612 $eventdata->userfrom = $user;
1613 $eventdata->userto = $teacher;
1614 $eventdata->subject = $postsubject;
1615 $eventdata->fullmessage = $posttext;
1616 $eventdata->fullmessageformat = FORMAT_PLAIN;
1617 $eventdata->fullmessagehtml = $posthtml;
1618 $eventdata->smallmessage = '';
1619 message_send($eventdata);
1625 * @param string $filearea
1626 * @param array $args
1629 function send_file($filearea, $args) {
1630 debugging('plugin does not implement file sending', DEBUG_DEVELOPER);
1635 * Returns a list of teachers that should be grading given submission
1637 * @param object $user
1640 function get_graders($user) {
1642 $potgraders = get_users_by_capability($this->context, 'mod/assignment:grade', '', '', '', '', '', '', false, false);
1645 if (groups_get_activity_groupmode($this->cm) == SEPARATEGROUPS) { // Separate groups are being used
1646 if ($groups = groups_get_all_groups($this->course->id, $user->id)) { // Try to find all groups
1647 foreach ($groups as $group) {
1648 foreach ($potgraders as $t) {
1649 if ($t->id == $user->id) {
1650 continue; // do not send self
1652 if (groups_is_member($group->id, $t->id)) {
1653 $graders[$t->id] = $t;
1658 // user not in group, try to find graders without group
1659 foreach ($potgraders as $t) {
1660 if ($t->id == $user->id) {
1661 continue; // do not send self
1663 if (!groups_get_all_groups($this->course->id, $t->id)) { //ugly hack
1664 $graders[$t->id] = $t;
1669 foreach ($potgraders as $t) {
1670 if ($t->id == $user->id) {
1671 continue; // do not send self
1673 $graders[$t->id] = $t;
1680 * Creates the text content for emails to teachers
1682 * @param $info object The info used by the 'emailteachermail' language string
1685 function email_teachers_text($info) {
1686 $posttext = format_string($this->course->shortname).' -> '.$this->strassignments.' -> '.
1687 format_string($this->assignment->name)."\n";
1688 $posttext .= '---------------------------------------------------------------------'."\n";
1689 $posttext .= get_string("emailteachermail", "assignment", $info)."\n";
1690 $posttext .= "\n---------------------------------------------------------------------\n";
1695 * Creates the html content for emails to teachers
1697 * @param $info object The info used by the 'emailteachermailhtml' language string
1700 function email_teachers_html($info) {
1702 $posthtml = '<p><font face="sans-serif">'.
1703 '<a href="'.$CFG->wwwroot.'/course/view.php?id='.$this->course->id.'">'.format_string($this->course->shortname).'</a> ->'.
1704 '<a href="'.$CFG->wwwroot.'/mod/assignment/index.php?id='.$this->course->id.'">'.$this->strassignments.'</a> ->'.
1705 '<a href="'.$CFG->wwwroot.'/mod/assignment/view.php?id='.$this->cm->id.'">'.format_string($this->assignment->name).'</a></font></p>';
1706 $posthtml .= '<hr /><font face="sans-serif">';
1707 $posthtml .= '<p>'.get_string('emailteachermailhtml', 'assignment', $info).'</p>';
1708 $posthtml .= '</font><hr />';
1713 * Produces a list of links to the files uploaded by a user
1715 * @param $userid int optional id of the user. If 0 then $USER->id is used.
1716 * @param $return boolean optional defaults to false. If true the list is returned rather than printed
1717 * @return string optional
1719 function print_user_files($userid=0, $return=false) {
1720 global $CFG, $USER, $OUTPUT;
1723 if (!isloggedin()) {
1726 $userid = $USER->id;
1731 $fs = get_file_storage();
1735 if ($files = $fs->get_area_files($this->context->id, 'mod_assignment', 'submission', $userid, "timemodified", false)) {
1736 require_once($CFG->libdir.'/portfoliolib.php');
1737 require_once($CFG->dirroot . '/mod/assignment/locallib.php');
1738 $button = new portfolio_add_button();
1739 foreach ($files as $file) {
1740 $filename = $file->get_filename();
1742 $mimetype = $file->get_mimetype();
1743 $path = file_encode_url($CFG->wwwroot.'/pluginfile.php', '/'.$this->context->id.'/mod_assignment/submission/'.$userid.'/'.$filename);
1744 $output .= '<a href="'.$path.'" ><img src="'.$OUTPUT->pix_url(file_mimetype_icon($mimetype)).'" class="icon" alt="'.$mimetype.'" />'.s($filename).'</a>';
1745 if ($this->portfolio_exportable() && has_capability('mod/assignment:exportownsubmission', $this->context)) {
1746 $button->set_callback_options('assignment_portfolio_caller', array('id' => $this->cm->id, 'fileid' => $file->get_id()), '/mod/assignment/locallib.php');
1747 $button->set_format_by_file($file);
1748 $output .= $button->to_html(PORTFOLIO_ADD_ICON_LINK);
1751 if (count($files) > 1 && $this->portfolio_exportable() && has_capability('mod/assignment:exportownsubmission', $this->context)) {
1752 $button->set_callback_options('assignment_portfolio_caller', array('id' => $this->cm->id), '/mod/assignment/locallib.php');
1753 $output .= '<br />' . $button->to_html();
1757 $output = '<div class="files">'.$output.'</div>';
1766 * Count the files uploaded by a given user
1768 * @param $userid int The user id
1771 function count_user_files($userid) {
1772 $fs = get_file_storage();
1773 $files = $fs->get_area_files($this->context->id, 'mod_assignment', 'submission', $userid, "id", false);
1774 return count($files);
1778 * Returns true if the student is allowed to submit
1780 * Checks that the assignment has started and, if the option to prevent late
1781 * submissions is set, also checks that the assignment has not yet closed.
1786 if ($this->assignment->preventlate && $this->assignment->timedue) {
1787 return ($this->assignment->timeavailable <= $time && $time <= $this->assignment->timedue);
1789 return ($this->assignment->timeavailable <= $time);
1795 * Return true if is set description is hidden till available date
1797 * This is needed by calendar so that hidden descriptions do not
1798 * come up in upcoming events.
1800 * Check that description is hidden till available date
1801 * By default return false
1802 * Assignments types should implement this method if needed
1805 function description_is_hidden() {
1810 * Return an outline of the user's interaction with the assignment
1812 * The default method prints the grade and timemodified
1813 * @param $grade object
1814 * @return object with properties ->info and ->time
1816 function user_outline($grade) {
1818 $result = new object();
1819 $result->info = get_string('grade').': '.$grade->str_long_grade;
1820 $result->time = $grade->dategraded;
1825 * Print complete information about the user's interaction with the assignment
1827 * @param $user object
1829 function user_complete($user, $grade=null) {
1832 echo $OUTPUT->container(get_string('grade').': '.$grade->str_long_grade);
1833 if ($grade->str_feedback) {
1834 echo $OUTPUT->container(get_string('feedback').': '.$grade->str_feedback);
1838 if ($submission = $this->get_submission($user->id)) {
1840 $fs = get_file_storage();
1842 if ($files = $fs->get_area_files($this->context->id, 'mod_assignment', 'submission', $user->id, "timemodified", false)) {
1843 $countfiles = count($files)." ".get_string("uploadedfiles", "assignment");
1844 foreach ($files as $file) {
1845 $countfiles .= "; ".$file->get_filename();
1849 echo $OUTPUT->box_start();
1850 echo get_string("lastmodified").": ";
1851 echo userdate($submission->timemodified);
1852 echo $this->display_lateness($submission->timemodified);
1854 $this->print_user_files($user->id);
1858 $this->view_feedback($submission);
1860 echo $OUTPUT->box_end();
1863 print_string("notsubmittedyet", "assignment");
1868 * Return a string indicating how late a submission is
1870 * @param $timesubmitted int
1873 function display_lateness($timesubmitted) {
1874 return assignment_display_lateness($timesubmitted, $this->assignment->timedue);
1878 * Empty method stub for all delete actions.
1881 //nothing by default
1882 redirect('view.php?id='.$this->cm->id);
1886 * Empty custom feedback grading form.
1888 function custom_feedbackform($submission, $return=false) {
1889 //nothing by default
1894 * Add a get_coursemodule_info function in case any assignment type wants to add 'extra' information
1895 * for the course (see resource).
1897 * Given a course_module object, this function returns any "extra" information that may be needed
1898 * when printing this activity in a course listing. See get_array_of_activities() in course/lib.php.
1900 * @param $coursemodule object The coursemodule object (record).
1901 * @return object An object on information that the coures will know about (most noticeably, an icon).
1904 function get_coursemodule_info($coursemodule) {
1909 * Plugin cron method - do not use $this here, create new assignment instances if needed.
1913 //no plugin cron by default - override if needed
1917 * Reset all submissions
1919 function reset_userdata($data) {
1922 if (!$DB->count_records('assignment', array('course'=>$data->courseid, 'assignmenttype'=>$this->type))) {
1923 return array(); // no assignments of this type present
1926 $componentstr = get_string('modulenameplural', 'assignment');
1929 $typestr = get_string('type'.$this->type, 'assignment');
1930 // ugly hack to support pluggable assignment type titles...
1931 if($typestr === '[[type'.$this->type.']]'){
1932 $typestr = get_string('type'.$this->type, 'assignment_'.$this->type);
1935 if (!empty($data->reset_assignment_submissions)) {
1936 $assignmentssql = "SELECT a.id
1938 WHERE a.course=? AND a.assignmenttype=?";
1939 $params = array($data->courseid, $this->type);
1941 // now get rid of all submissions and responses
1942 $fs = get_file_storage();
1943 if ($assignments = $DB->get_records_sql($assignmentssql, $params)) {
1944 foreach ($assignments as $assignmentid=>$unused) {
1945 if (!$cm = get_coursemodule_from_instance('assignment', $assignmentid)) {
1948 $context = get_context_instance(CONTEXT_MODULE, $cm->id);
1949 $fs->delete_area_files($context->id, 'mod_assignment', 'submission');
1950 $fs->delete_area_files($context->id, 'mod_assignment', 'response');
1954 $DB->delete_records_select('assignment_submissions', "assignment IN ($assignmentssql)", $params);
1956 $status[] = array('component'=>$componentstr, 'item'=>get_string('deleteallsubmissions','assignment').': '.$typestr, 'error'=>false);
1958 if (empty($data->reset_gradebook_grades)) {
1959 // remove all grades from gradebook
1960 assignment_reset_gradebook($data->courseid, $this->type);
1964 /// updating dates - shift may be negative too
1965 if ($data->timeshift) {
1966 shift_course_mod_dates('assignment', array('timedue', 'timeavailable'), $data->timeshift, $data->courseid);
1967 $status[] = array('component'=>$componentstr, 'item'=>get_string('datechanged').': '.$typestr, 'error'=>false);
1974 function portfolio_exportable() {
1979 * base implementation for backing up subtype specific information
1980 * for one single module
1982 * @param filehandle $bf file handle for xml file to write to
1983 * @param mixed $preferences the complete backup preference object
1989 static function backup_one_mod($bf, $preferences, $assignment) {
1994 * base implementation for backing up subtype specific information
1995 * for one single submission
1997 * @param filehandle $bf file handle for xml file to write to
1998 * @param mixed $preferences the complete backup preference object
1999 * @param object $submission the assignment submission db record
2005 static function backup_one_submission($bf, $preferences, $assignment, $submission) {
2010 * base implementation for restoring subtype specific information
2011 * for one single module
2013 * @param array $info the array representing the xml
2014 * @param object $restore the restore preferences
2020 static function restore_one_mod($info, $restore, $assignment) {
2025 * base implementation for restoring subtype specific information
2026 * for one single submission
2028 * @param object $submission the newly created submission
2029 * @param array $info the array representing the xml
2030 * @param object $restore the restore preferences
2036 static function restore_one_submission($info, $restore, $assignment, $submission) {
2040 } ////// End of the assignment_base class
2043 class mod_assignment_online_grading_form extends moodleform { // TODO: why "online" in the name of this class? (skodak)
2045 function definition() {
2047 $mform =& $this->_form;
2049 $formattr = $mform->getAttributes();
2050 $formattr['id'] = 'submitform';
2051 $mform->setAttributes($formattr);
2053 $mform->addElement('hidden', 'offset', ($this->_customdata->offset+1));
2054 $mform->setType('offset', PARAM_INT);
2055 $mform->addElement('hidden', 'userid', $this->_customdata->userid);
2056 $mform->setType('userid', PARAM_INT);
2057 $mform->addElement('hidden', 'nextid', $this->_customdata->nextid);
2058 $mform->setType('nextid', PARAM_INT);
2059 $mform->addElement('hidden', 'id', $this->_customdata->cm->id);
2060 $mform->setType('id', PARAM_INT);
2061 $mform->addElement('hidden', 'sesskey', sesskey());
2062 $mform->setType('sesskey', PARAM_ALPHANUM);
2063 $mform->addElement('hidden', 'mode', 'grade');
2064 $mform->setType('mode', PARAM_INT);
2065 $mform->addElement('hidden', 'menuindex', "0");
2066 $mform->setType('menuindex', PARAM_INT);
2067 $mform->addElement('hidden', 'saveuserid', "-1");
2068 $mform->setType('saveuserid', PARAM_INT);
2070 $mform->addElement('static', 'picture', $OUTPUT->user_picture($this->_customdata->user),
2071 fullname($this->_customdata->user, true) . '<br/>' .
2072 userdate($this->_customdata->submission->timemodified) .
2073 $this->_customdata->lateness );
2075 $this->add_grades_section();
2077 $this->add_feedback_section();
2079 if ($this->_customdata->submission->timemarked) {
2080 $mform->addElement('header', 'Last Grade', get_string('lastgrade', 'assignment'));
2081 $mform->addElement('static', 'picture', $OUTPUT->user_picture($this->_customdata->teacher) ,
2082 fullname($this->_customdata->teacher,true).
2084 userdate($this->_customdata->submission->timemarked));
2087 $this->add_action_buttons();
2089 $this->add_submission_content();
2092 function add_grades_section() {
2094 $mform =& $this->_form;
2095 $attributes = array();
2096 if ($this->_customdata->gradingdisabled) {
2097 $attributes['disabled'] ='disabled';
2100 $grademenu = make_grades_menu($this->_customdata->assignment->grade);
2101 $grademenu['-1'] = get_string('nograde');
2103 $mform->addElement('header', 'Grades', get_string('grades', 'grades'));
2104 $mform->addElement('select', 'xgrade', get_string('grade').':', $grademenu, $attributes);
2105 $mform->setDefault('xgrade', $this->_customdata->submission->grade ); //@fixme some bug when element called 'grade' makes it break
2106 $mform->setType('xgrade', PARAM_INT);
2108 if (!empty($this->_customdata->enableoutcomes)) {
2109 foreach($this->_customdata->grading_info->outcomes as $n=>$outcome) {
2110 $options = make_grades_menu(-$outcome->scaleid);
2111 if ($outcome->grades[$this->_customdata->submission->userid]->locked) {
2112 $options[0] = get_string('nooutcome', 'grades');
2113 echo $options[$outcome->grades[$this->_customdata->submission->userid]->grade];
2115 $options[''] = get_string('nooutcome', 'grades');
2116 $attributes = array('id' => 'menuoutcome_'.$n );
2117 $mform->addElement('select', 'outcome_'.$n.'['.$this->_customdata->userid.']', $outcome->name.':', $options, $attributes );
2118 $mform->setType('outcome_'.$n.'['.$this->_customdata->userid.']', PARAM_INT);
2119 $mform->setDefault('outcome_'.$n.'['.$this->_customdata->userid.']', $outcome->grades[$this->_customdata->submission->userid]->grade );
2123 $course_context = get_context_instance(CONTEXT_MODULE , $this->_customdata->cm->id);
2124 if (has_capability('gradereport/grader:view', $course_context) && has_capability('moodle/grade:viewall', $course_context)) {
2125 $grade = '<a href="'.$CFG->wwwroot.'/grade/report/grader/index.php?id='. $this->_customdata->courseid .'" >'.
2126 $this->_customdata->grading_info->items[0]->grades[$this->_customdata->userid]->str_grade . '</a>';
2128 $grade = $this->_customdata->grading_info->items[0]->grades[$this->_customdata->userid]->str_grade;
2130 $mform->addElement('static', 'finalgrade', get_string('currentgrade', 'assignment').':' ,$grade);
2131 $mform->setType('finalgrade', PARAM_INT);
2136 * @global core_renderer $OUTPUT
2138 function add_feedback_section() {
2140 $mform =& $this->_form;
2141 $mform->addElement('header', 'Feed Back', get_string('feedback', 'grades'));
2143 if ($this->_customdata->gradingdisabled) {
2144 $mform->addElement('static', 'disabledfeedback', $this->_customdata->grading_info->items[0]->grades[$this->_customdata->userid]->str_feedback );
2148 $mform->addElement('editor', 'submissioncomment_editor', get_string('feedback', 'assignment').':', null, $this->get_editor_options() );
2149 $mform->setType('submissioncomment_editor', PARAM_RAW); // to be cleaned before display
2150 $mform->setDefault('submissioncomment_editor', $this->_customdata->submission->submissioncomment);
2151 //$mform->addRule('submissioncomment', get_string('required'), 'required', null, 'client');
2153 if ($this->_customdata->usehtmleditor) {
2154 $mform->addElement('hidden', 'format', FORMAT_HTML);
2155 $mform->setType('format', PARAM_INT);
2158 $format_menu = format_text_menu();
2159 $mform->addElement('select', 'format', get_string('format'), $format_menu, array('selected' => $this->_customdata->submission->format ) );
2160 $mform->setType('format', PARAM_INT);
2162 $lastmailinfo = get_user_preferences('assignment_mailinfo', 1) ? array('checked'=>'checked') : array();
2163 $mform->addElement('hidden', 'mailinfo_h', "0");
2164 $mform->setType('mailinfo_h', PARAM_INT);
2165 $mform->addElement('checkbox', 'mailinfo',get_string('enableemailnotification','assignment').
2166 $OUTPUT->help_icon('enableemailnotification', 'assignment') .':' );
2167 $mform->updateElementAttr('mailinfo', $lastmailinfo);
2168 $mform->setType('mailinfo', PARAM_INT);
2172 function add_action_buttons() {
2173 $mform =& $this->_form;
2174 $mform->addElement('header', 'Operation', get_string('operation', 'assignment'));
2175 //if there are more to be graded.
2176 if ($this->_customdata->nextid>0) {
2177 $buttonarray=array();
2178 $buttonarray[] = &$mform->createElement('submit', 'submitbutton', get_string('savechanges'));
2179 //@todo: fix accessibility: javascript dependency not necessary
2180 $buttonarray[] = &$mform->createElement('submit', 'saveandnext', get_string('saveandnext'));
2181 $buttonarray[] = &$mform->createElement('submit', 'next', get_string('next'));
2182 $buttonarray[] = &$mform->createElement('cancel');
2184 $buttonarray=array();
2185 $buttonarray[] = &$mform->createElement('submit', 'submitbutton', get_string('savechanges'));
2186 $buttonarray[] = &$mform->createElement('cancel');
2188 $mform->addGroup($buttonarray, 'grading_buttonar', '', array(' '), false);
2189 $mform->setType('grading_buttonar', PARAM_RAW);
2192 function add_submission_content() {
2193 $mform =& $this->_form;
2194 $mform->addElement('header', 'Submission', get_string('submission', 'assignment'));
2195 $mform->addElement('static', '', '' , $this->_customdata->submission_content );
2198 protected function get_editor_options() {
2199 $editoroptions = array();
2200 $editoroptions['component'] = 'mod_assignment';
2201 $editoroptions['filearea'] = 'feedback';
2202 $editoroptions['noclean'] = false;
2203 $editoroptions['maxfiles'] = 0; //TODO: no files for now, we need to first implement assignment_feedback area, integration with gradebook, files support in quickgrading, etc. (skodak)
2204 $editoroptions['maxbytes'] = $this->_customdata->maxbytes;
2205 return $editoroptions;
2208 public function set_data($data) {
2209 $editoroptions = $this->get_editor_options();
2210 if (!isset($data->text)) {
2213 if (!isset($data->format)) {
2214 $data->textformat = FORMAT_HTML;
2216 $data->textformat = $data->format;
2219 if (!empty($this->_customdata->submission->id)) {
2220 $itemid = $this->_customdata->submission->id;
2225 $data = file_prepare_standard_editor($data, 'submissioncomment', $editoroptions, $this->_customdata->context, $editoroptions['component'], $editoroptions['filearea'], $itemid);
2226 return parent::set_data($data);
2229 public function get_data() {
2230 $data = parent::get_data();
2232 if (!empty($this->_customdata->submission->id)) {
2233 $itemid = $this->_customdata->submission->id;
2235 $itemid = null; //TODO: this is wrong, itemid MUST be known when saving files!! (skodak)
2239 $editoroptions = $this->get_editor_options();
2240 $data = file_postupdate_standard_editor($data, 'submissioncomment', $editoroptions, $this->_customdata->context, $editoroptions['component'], $editoroptions['filearea'], $itemid);
2241 $data->format = $data->textformat;
2247 /// OTHER STANDARD FUNCTIONS ////////////////////////////////////////////////////////
2250 * Deletes an assignment instance
2252 * This is done by calling the delete_instance() method of the assignment type class
2254 function assignment_delete_instance($id){
2257 if (! $assignment = $DB->get_record('assignment', array('id'=>$id))) {
2261 // fall back to base class if plugin missing
2262 $classfile = "$CFG->dirroot/mod/assignment/type/$assignment->assignmenttype/assignment.class.php";
2263 if (file_exists($classfile)) {
2264 require_once($classfile);
2265 $assignmentclass = "assignment_$assignment->assignmenttype";
2268 debugging("Missing assignment plug-in: {$assignment->assignmenttype}. Using base class for deleting instead.");
2269 $assignmentclass = "assignment_base";
2272 $ass = new $assignmentclass();
2273 return $ass->delete_instance($assignment);
2278 * Updates an assignment instance
2280 * This is done by calling the update_instance() method of the assignment type class
2282 function assignment_update_instance($assignment){
2285 $assignment->assignmenttype = clean_param($assignment->assignmenttype, PARAM_SAFEDIR);
2287 require_once("$CFG->dirroot/mod/assignment/type/$assignment->assignmenttype/assignment.class.php");
2288 $assignmentclass = "assignment_$assignment->assignmenttype";
2289 $ass = new $assignmentclass();
2290 return $ass->update_instance($assignment);
2295 * Adds an assignment instance
2297 * This is done by calling the add_instance() method of the assignment type class
2299 function assignment_add_instance($assignment) {
2302 $assignment->assignmenttype = clean_param($assignment->assignmenttype, PARAM_SAFEDIR);
2304 require_once("$CFG->dirroot/mod/assignment/type/$assignment->assignmenttype/assignment.class.php");
2305 $assignmentclass = "assignment_$assignment->assignmenttype";
2306 $ass = new $assignmentclass();
2307 return $ass->add_instance($assignment);
2312 * Returns an outline of a user interaction with an assignment
2314 * This is done by calling the user_outline() method of the assignment type class
2316 function assignment_user_outline($course, $user, $mod, $assignment) {
2319 require_once("$CFG->libdir/gradelib.php");
2320 require_once("$CFG->dirroot/mod/assignment/type/$assignment->assignmenttype/assignment.class.php");
2321 $assignmentclass = "assignment_$assignment->assignmenttype";
2322 $ass = new $assignmentclass($mod->id, $assignment, $mod, $course);
2323 $grades = grade_get_grades($course->id, 'mod', 'assignment', $assignment->id, $user->id);
2324 if (!empty($grades->items[0]->grades)) {
2325 return $ass->user_outline(reset($grades->items[0]->grades));
2332 * Prints the complete info about a user's interaction with an assignment
2334 * This is done by calling the user_complete() method of the assignment type class
2336 function assignment_user_complete($course, $user, $mod, $assignment) {
2339 require_once("$CFG->libdir/gradelib.php");
2340 require_once("$CFG->dirroot/mod/assignment/type/$assignment->assignmenttype/assignment.class.php");
2341 $assignmentclass = "assignment_$assignment->assignmenttype";
2342 $ass = new $assignmentclass($mod->id, $assignment, $mod, $course);
2343 $grades = grade_get_grades($course->id, 'mod', 'assignment', $assignment->id, $user->id);
2344 if (empty($grades->items[0]->grades)) {
2347 $grade = reset($grades->items[0]->grades);
2349 return $ass->user_complete($user, $grade);
2353 * Function to be run periodically according to the moodle cron
2355 * Finds all assignment notifications that have yet to be mailed out, and mails them
2357 function assignment_cron () {
2358 global $CFG, $USER, $DB;
2360 /// first execute all crons in plugins
2361 if ($plugins = get_plugin_list('assignment')) {
2362 foreach ($plugins as $plugin=>$dir) {
2363 require_once("$dir/assignment.class.php");
2364 $assignmentclass = "assignment_$plugin";
2365 $ass = new $assignmentclass();
2370 /// Notices older than 1 day will not be mailed. This is to avoid the problem where
2371 /// cron has not been running for a long time, and then suddenly people are flooded
2372 /// with mail from the past few weeks or months
2375 $endtime = $timenow - $CFG->maxeditingtime;
2376 $starttime = $endtime - 24 * 3600; /// One day earlier
2378 if ($submissions = assignment_get_unmailed_submissions($starttime, $endtime)) {
2380 $realuser = clone($USER);
2382 foreach ($submissions as $key => $submission) {
2383 if (! $DB->set_field("assignment_submissions", "mailed", "1", array("id"=>$submission->id))) {
2384 echo "Could not update the mailed field for id $submission->id. Not mailed.\n";
2385 unset($submissions[$key]);
2391 foreach ($submissions as $submission) {
2393 echo "Processing assignment submission $submission->id\n";
2395 if (! $user = $DB->get_record("user", array("id"=>$submission->userid))) {
2396 echo "Could not find user $post->userid\n";
2400 if (! $course = $DB->get_record("course", array("id"=>$submission->course))) {
2401 echo "Could not find course $submission->course\n";
2405 /// Override the language and timezone of the "current" user, so that
2406 /// mail is customised for the receiver.
2407 cron_setup_user($user, $course);
2409 if (!is_enrolled(get_context_instance(CONTEXT_COURSE, $submission->course), $user->id)) {
2410 echo fullname($user)." not an active participant in " . format_string($course->shortname) . "\n";
2414 if (! $teacher = $DB->get_record("user", array("id"=>$submission->teacher))) {
2415 echo "Could not find teacher $submission->teacher\n";
2419 if (! $mod = get_coursemodule_from_instance("assignment", $submission->assignment, $course->id)) {
2420 echo "Could not find course module for assignment id $submission->assignment\n";
2424 if (! $mod->visible) { /// Hold mail notification for hidden assignments until later
2428 $strassignments = get_string("modulenameplural", "assignment");
2429 $strassignment = get_string("modulename", "assignment");
2431 $assignmentinfo = new object();
2432 $assignmentinfo->teacher = fullname($teacher);
2433 $assignmentinfo->assignment = format_string($submission->name,true);
2434 $assignmentinfo->url = "$CFG->wwwroot/mod/assignment/view.php?id=$mod->id";
2436 $postsubject = "$course->shortname: $strassignments: ".format_string($submission->name,true);
2437 $posttext = "$course->shortname -> $strassignments -> ".format_string($submission->name,true)."\n";
2438 $posttext .= "---------------------------------------------------------------------\n";
2439 $posttext .= get_string("assignmentmail", "assignment", $assignmentinfo)."\n";
2440 $posttext .= "---------------------------------------------------------------------\n";
2442 if ($user->mailformat == 1) { // HTML
2443 $posthtml = "<p><font face=\"sans-serif\">".
2444 "<a href=\"$CFG->wwwroot/course/view.php?id=$course->id\">$course->shortname</a> ->".
2445 "<a href=\"$CFG->wwwroot/mod/assignment/index.php?id=$course->id\">$strassignments</a> ->".
2446 "<a href=\"$CFG->wwwroot/mod/assignment/view.php?id=$mod->id\">".format_string($submission->name,true)."</a></font></p>";
2447 $posthtml .= "<hr /><font face=\"sans-serif\">";
2448 $posthtml .= "<p>".get_string("assignmentmailhtml", "assignment", $assignmentinfo)."</p>";
2449 $posthtml .= "</font><hr />";
2454 $eventdata = new object();
2455 $eventdata->modulename = 'assignment';
2456 $eventdata->userfrom = $teacher;
2457 $eventdata->userto = $user;
2458 $eventdata->subject = $postsubject;
2459 $eventdata->fullmessage = $posttext;
2460 $eventdata->fullmessageformat = FORMAT_PLAIN;
2461 $eventdata->fullmessagehtml = $posthtml;
2462 $eventdata->smallmessage = '';
2463 message_send($eventdata);
2473 * Return grade for given user or all users.
2475 * @param int $assignmentid id of assignment
2476 * @param int $userid optional user id, 0 means all users
2477 * @return array array of grades, false if none
2479 function assignment_get_user_grades($assignment, $userid=0) {
2483 $user = "AND u.id = :userid";
2484 $params = array('userid'=>$userid);
2488 $params['aid'] = $assignment->id;
2490 $sql = "SELECT u.id, u.id AS userid, s.grade AS rawgrade, s.submissioncomment AS feedback, s.format AS feedbackformat,
2491 s.teacher AS usermodified, s.timemarked AS dategraded, s.timemodified AS datesubmitted
2492 FROM {user} u, {assignment_submissions} s
2493 WHERE u.id = s.userid AND s.assignment = :aid
2496 return $DB->get_records_sql($sql, $params);
2500 * Update activity grades
2502 * @param object $assignment
2503 * @param int $userid specific user only, 0 means all
2505 function assignment_update_grades($assignment, $userid=0, $nullifnone=true) {
2507 require_once($CFG->libdir.'/gradelib.php');
2509 if ($assignment->grade == 0) {
2510 assignment_grade_item_update($assignment);
2512 } else if ($grades = assignment_get_user_grades($assignment, $userid)) {
2513 foreach($grades as $k=>$v) {
2514 if ($v->rawgrade == -1) {
2515 $grades[$k]->rawgrade = null;
2518 assignment_grade_item_update($assignment, $grades);
2521 assignment_grade_item_update($assignment);
2526 * Update all grades in gradebook.
2528 function assignment_upgrade_grades() {
2531 $sql = "SELECT COUNT('x')
2532 FROM {assignment} a, {course_modules} cm, {modules} m
2533 WHERE m.name='assignment' AND m.id=cm.module AND cm.instance=a.id";
2534 $count = $DB->count_records_sql($sql);
2536 $sql = "SELECT a.*, cm.idnumber AS cmidnumber, a.course AS courseid
2537 FROM {assignment} a, {course_modules} cm, {modules} m
2538 WHERE m.name='assignment' AND m.id=cm.module AND cm.instance=a.id";
2539 if ($rs = $DB->get_recordset_sql($sql)) {
2540 // too much debug output
2541 $pbar = new progress_bar('assignmentupgradegrades', 500, true);
2543 foreach ($rs as $assignment) {
2545 upgrade_set_timeout(60*5); // set up timeout, may also abort execution
2546 assignment_update_grades($assignment);
2547 $pbar->update($i, $count, "Updating Assignment grades ($i/$count).");
2550 upgrade_set_timeout(); // reset to default timeout
2555 * Create grade item for given assignment
2557 * @param object $assignment object with extra cmidnumber
2558 * @param mixed optional array/object of grade(s); 'reset' means reset grades in gradebook
2559 * @return int 0 if ok, error code otherwise
2561 function assignment_grade_item_update($assignment, $grades=NULL) {
2563 require_once($CFG->libdir.'/gradelib.php');
2565 if (!isset($assignment->courseid)) {
2566 $assignment->courseid = $assignment->course;
2569 $params = array('itemname'=>$assignment->name, 'idnumber'=>$assignment->cmidnumber);
2571 if ($assignment->grade > 0) {
2572 $params['gradetype'] = GRADE_TYPE_VALUE;
2573 $params['grademax'] = $assignment->grade;
2574 $params['grademin'] = 0;
2576 } else if ($assignment->grade < 0) {
2577 $params['gradetype'] = GRADE_TYPE_SCALE;
2578 $params['scaleid'] = -$assignment->grade;
2581 $params['gradetype'] = GRADE_TYPE_TEXT; // allow text comments only
2584 if ($grades === 'reset') {
2585 $params['reset'] = true;
2589 return grade_update('mod/assignment', $assignment->courseid, 'mod', 'assignment', $assignment->id, 0, $grades, $params);
2593 * Delete grade item for given assignment
2595 * @param object $assignment object
2596 * @return object assignment
2598 function assignment_grade_item_delete($assignment) {
2600 require_once($CFG->libdir.'/gradelib.php');
2602 if (!isset($assignment->courseid)) {
2603 $assignment->courseid = $assignment->course;
2606 return grade_update('mod/assignment', $assignment->courseid, 'mod', 'assignment', $assignment->id, 0, NULL, array('deleted'=>1));
2610 * Returns the users with data in one assignment (students and teachers)
2612 * @param $assignmentid int
2613 * @return array of user objects
2615 function assignment_get_participants($assignmentid) {
2619 $students = $DB->get_records_sql("SELECT DISTINCT u.id, u.id
2621 {assignment_submissions} a
2622 WHERE a.assignment = ? and
2623 u.id = a.userid", array($assignmentid));
2625 $teachers = $DB->get_records_sql("SELECT DISTINCT u.id, u.id
2627 {assignment_submissions} a
2628 WHERE a.assignment = ? and
2629 u.id = a.teacher", array($assignmentid));
2631 //Add teachers to students
2633 foreach ($teachers as $teacher) {
2634 $students[$teacher->id] = $teacher;
2637 //Return students array (it contains an array of unique users)
2642 * Serves assignment submissions and other files.
2644 * @param object $course
2646 * @param object $context
2647 * @param string $filearea
2648 * @param array $args
2649 * @param bool $forcedownload
2650 * @return bool false if file not found, does not return if found - just send the file
2652 function assignment_pluginfile($course, $cm, $context, $filearea, $args, $forcedownload) {
2655 if ($context->contextlevel != CONTEXT_MODULE) {
2659 require_login($course, false, $cm);
2661 if (!$assignment = $DB->get_record('assignment', array('id'=>$cm->instance))) {
2665 require_once($CFG->dirroot.'/mod/assignment/type/'.$assignment->assignmenttype.'/assignment.class.php');
2666 $assignmentclass = 'assignment_'.$assignment->assignmenttype;
2667 $assignmentinstance = new $assignmentclass($cm->id, $assignment, $cm, $course);
2669 return $assignmentinstance->send_file($filearea, $args);
2672 * Checks if a scale is being used by an assignment
2674 * This is used by the backup code to decide whether to back up a scale
2675 * @param $assignmentid int
2676 * @param $scaleid int
2677 * @return boolean True if the scale is used by the assignment
2679 function assignment_scale_used($assignmentid, $scaleid) {
2684 $rec = $DB->get_record('assignment', array('id'=>$assignmentid,'grade'=>-$scaleid));
2686 if (!empty($rec) && !empty($scaleid)) {
2694 * Checks if scale is being used by any instance of assignment
2696 * This is used to find out if scale used anywhere
2697 * @param $scaleid int
2698 * @return boolean True if the scale is used by any assignment
2700 function assignment_scale_used_anywhere($scaleid) {
2703 if ($scaleid and $DB->record_exists('assignment', array('grade'=>-$scaleid))) {
2711 * Make sure up-to-date events are created for all assignment instances
2713 * This standard function will check all instances of this module
2714 * and make sure there are up-to-date events created for each of them.
2715 * If courseid = 0, then every assignment event in the site is checked, else
2716 * only assignment events belonging to the course specified are checked.
2717 * This function is used, in its new format, by restore_refresh_events()
2719 * @param $courseid int optional If zero then all assignments for all courses are covered
2720 * @return boolean Always returns true
2722 function assignment_refresh_events($courseid = 0) {
2725 if ($courseid == 0) {
2726 if (! $assignments = $DB->get_records("assignment")) {
2730 if (! $assignments = $DB->get_records("assignment", array("course"=>$courseid))) {
2734 $moduleid = $DB->get_field('modules', 'id', array('name'=>'assignment'));
2736 foreach ($assignments as $assignment) {
2737 $cm = get_coursemodule_from_id('assignment', $assignment->id);
2738 $event = new object();
2739 $event->name = $assignment->name;
2740 $event->description = format_module_intro('assignment', $assignment, $cm->id);
2741 $event->timestart = $assignment->timedue;
2743 if ($event->id = $DB->get_field('event', 'id', array('modulename'=>'assignment', 'instance'=>$assignment->id))) {
2744 update_event($event);
2747 $event->courseid = $assignment->course;
2748 $event->groupid = 0;
2750 $event->modulename = 'assignment';
2751 $event->instance = $assignment->id;
2752 $event->eventtype = 'due';
2753 $event->timeduration = 0;
2754 $event->visible = $DB->get_field('course_modules', 'visible', array('module'=>$moduleid, 'instance'=>$assignment->id));
2763 * Print recent activity from all assignments in a given course
2765 * This is used by the recent activity block
2767 function assignment_print_recent_activity($course, $viewfullnames, $timestart) {
2768 global $CFG, $USER, $DB, $OUTPUT;
2770 // do not use log table if possible, it may be huge
2772 if (!$submissions = $DB->get_records_sql("SELECT asb.id, asb.timemodified, cm.id AS cmid, asb.userid,
2773 u.firstname, u.lastname, u.email, u.picture
2774 FROM {assignment_submissions} asb
2775 JOIN {assignment} a ON a.id = asb.assignment
2776 JOIN {course_modules} cm ON cm.instance = a.id
2777 JOIN {modules} md ON md.id = cm.module
2778 JOIN {user} u ON u.id = asb.userid
2779 WHERE asb.timemodified > ? AND
2781 md.name = 'assignment'
2782 ORDER BY asb.timemodified ASC", array($timestart, $course->id))) {
2786 $modinfo =& get_fast_modinfo($course); // reference needed because we might load the groups
2790 foreach($submissions as $submission) {
2791 if (!array_key_exists($submission->cmid, $modinfo->cms)) {
2794 $cm = $modinfo->cms[$submission->cmid];
2795 if (!$cm->uservisible) {
2798 if ($submission->userid == $USER->id) {
2799 $show[] = $submission;
2803 // the act of sumbitting of assignment may be considered private - only graders will see it if specified
2804 if (empty($CFG->assignment_showrecentsubmissions)) {
2805 if (!array_key_exists($cm->id, $grader)) {
2806 $grader[$cm->id] = has_capability('moodle/grade:viewall', get_context_instance(CONTEXT_MODULE, $cm->id));
2808 if (!$grader[$cm->id]) {
2813 $groupmode = groups_get_activity_groupmode($cm, $course);
2815 if ($groupmode == SEPARATEGROUPS and !has_capability('moodle/site:accessallgroups', get_context_instance(CONTEXT_MODULE, $cm->id))) {
2816 if (isguestuser()) {
2817 // shortcut - guest user does not belong into any group
2821 if (is_null($modinfo->groups)) {
2822 $modinfo->groups = groups_get_user_groups($course->id); // load all my groups and cache it in modinfo
2825 // this will be slow - show only users that share group with me in this cm
2826 if (empty($modinfo->groups[$cm->id])) {
2829 $usersgroups = groups_get_all_groups($course->id, $cm->userid, $cm->groupingid);
2830 if (is_array($usersgroups)) {
2831 $usersgroups = array_keys($usersgroups);
2832 $interset = array_intersect($usersgroups, $modinfo->groups[$cm->id]);
2833 if (empty($intersect)) {
2838 $show[] = $submission;
2845 echo $OUTPUT->heading(get_string('newsubmissions', 'assignment').':');
2847 foreach ($show as $submission) {
2848 $cm = $modinfo->cms[$submission->cmid];
2849 $link = $CFG->wwwroot.'/mod/assignment/view.php?id='.$cm->id;
2850 print_recent_activity_note($submission->timemodified, $submission, $cm->name, $link, false, $viewfullnames);
2858 * Returns all assignments since a given time in specified forum.
2860 function assignment_get_recent_mod_activity(&$activities, &$index, $timestart, $courseid, $cmid, $userid=0, $groupid=0) {
2861 global $CFG, $COURSE, $USER, $DB;
2863 if ($COURSE->id == $courseid) {
2866 $course = $DB->get_record('course', array('id'=>$courseid));
2869 $modinfo =& get_fast_modinfo($course);
2871 $cm = $modinfo->cms[$cmid];
2875 $userselect = "AND u.id = :userid";
2876 $params['userid'] = $userid;
2882 $groupselect = "AND gm.groupid = :groupid";
2883 $groupjoin = "JOIN {groups_members} gm ON gm.userid=u.id";
2884 $params['groupid'] = $groupid;
2890 $params['cminstance'] = $cm->instance;
2891 $params['timestart'] = $timestart;
2893 if (!$submissions = $DB->get_records_sql("SELECT asb.id, asb.timemodified, asb.userid,
2894 u.firstname, u.lastname, u.email, u.picture
2895 FROM {assignment_submissions} asb
2896 JOIN {assignment} a ON a.id = asb.assignment
2897 JOIN {user} u ON u.id = asb.userid
2899 WHERE asb.timemodified > :timestart AND a.id = :cminstance
2900 $userselect $groupselect
2901 ORDER BY asb.timemodified ASC", $params)) {
2905 $groupmode = groups_get_activity_groupmode($cm, $course);
2906 $cm_context = get_context_instance(CONTEXT_MODULE, $cm->id);
2907 $grader = has_capability('moodle/grade:viewall', $cm_context);
2908 $accessallgroups = has_capability('moodle/site:accessallgroups', $cm_context);
2909 $viewfullnames = has_capability('moodle/site:viewfullnames', $cm_context);
2911 if (is_null($modinfo->groups)) {
2912 $modinfo->groups = groups_get_user_groups($course->id); // load all my groups and cache it in modinfo
2917 foreach($submissions as $submission) {
2918 if ($submission->userid == $USER->id) {
2919 $show[] = $submission;
2922 // the act of submitting of assignment may be considered private - only graders will see it if specified
2923 if (empty($CFG->assignment_showrecentsubmissions)) {
2929 if ($groupmode == SEPARATEGROUPS and !$accessallgroups) {
2930 if (isguestuser()) {
2931 // shortcut - guest user does not belong into any group
2935 // this will be slow - show only users that share group with me in this cm
2936 if (empty($modinfo->groups[$cm->id])) {
2939 $usersgroups = groups_get_all_groups($course->id, $cm->userid, $cm->groupingid);
2940 if (is_array($usersgroups)) {
2941 $usersgroups = array_keys($usersgroups);
2942 $interset = array_intersect($usersgroups, $modinfo->groups[$cm->id]);
2943 if (empty($intersect)) {
2948 $show[] = $submission;
2956 require_once($CFG->libdir.'/gradelib.php');
2958 foreach ($show as $id=>$submission) {
2959 $userids[] = $submission->userid;
2962 $grades = grade_get_grades($courseid, 'mod', 'assignment', $cm->instance, $userids);
2965 $aname = format_string($cm->name,true);
2966 foreach ($show as $submission) {
2967 $tmpactivity = new object();
2969 $tmpactivity->type = 'assignment';
2970 $tmpactivity->cmid = $cm->id;
2971 $tmpactivity->name = $aname;
2972 $tmpactivity->sectionnum = $cm->sectionnum;
2973 $tmpactivity->timestamp = $submission->timemodified;
2976 $tmpactivity->grade = $grades->items[0]->grades[$submission->userid]->str_long_grade;
2979 $tmpactivity->user->userid = $submission->userid;
2980 $tmpactivity->user->fullname = fullname($submission, $viewfullnames);
2981 $tmpactivity->user->picture = $submission->picture;
2983 $activities[$index++] = $tmpactivity;
2990 * Print recent activity from all assignments in a given course
2992 * This is used by course/recent.php
2994 function assignment_print_recent_mod_activity($activity, $courseid, $detail, $modnames) {
2995 global $CFG, $OUTPUT;
2997 echo '<table border="0" cellpadding="3" cellspacing="0" class="assignment-recent">';
2999 echo "<tr><td class=\"userpicture\" valign=\"top\">";
3000 echo $OUTPUT->user_picture($activity->user);
3004 $modname = $modnames[$activity->type];
3005 echo '<div class="title">';
3006 echo "<img src=\"" . $OUTPUT->pix_url('icon', 'assignment') . "\" ".
3007 "class=\"icon\" alt=\"$modname\">";
3008 echo "<a href=\"$CFG->wwwroot/mod/assignment/view.php?id={$activity->cmid}\">{$activity->name}</a>";
3012 if (isset($activity->grade)) {
3013 echo '<div class="grade">';
3014 echo get_string('grade').': ';
3015 echo $activity->grade;
3019 echo '<div class="user">';
3020 echo "<a href=\"$CFG->wwwroot/user/view.php?id={$activity->user->userid}&course=$courseid\">"
3021 ."{$activity->user->fullname}</a> - ".userdate($activity->timestamp);
3024 echo "</td></tr></table>";
3027 /// GENERIC SQL FUNCTIONS
3030 * Fetch info from logs
3032 * @param $log object with properties ->info (the assignment id) and ->userid
3033 * @return array with assignment name and user firstname and lastname
3035 function assignment_log_info($log) {
3038 return $DB->get_record_sql("SELECT a.name, u.firstname, u.lastname
3039 FROM {assignment} a, {user} u
3040 WHERE a.id = ? AND u.id = ?", array($log->info, $log->userid));
3044 * Return list of marked submissions that have not been mailed out for currently enrolled students
3048 function assignment_get_unmailed_submissions($starttime, $endtime) {
3051 return $DB->get_records_sql("SELECT s.*, a.course, a.name
3052 FROM {assignment_submissions} s,
3055 AND s.timemarked <= ?
3056 AND s.timemarked >= ?
3057 AND s.assignment = a.id", array($endtime, $starttime));
3061 * Counts all real assignment submissions by ENROLLED students (not empty ones)
3063 * There are also assignment type methods count_real_submissions() wich in the default
3064 * implementation simply call this function.
3065 * @param $groupid int optional If nonzero then count is restricted to this group
3066 * @return int The number of submissions
3068 function assignment_count_real_submissions($cm, $groupid=0) {
3071 $context = get_context_instance(CONTEXT_MODULE, $cm->id);
3073 // this is all the users with this capability set, in this context or higher
3074 if ($users = get_enrolled_users($context, 'mod/assignment:submit', $groupid, 'u.id')) {
3075 $users = array_keys($users);
3078 // if groupmembersonly used, remove users who are not in any group
3079 if ($users and !empty($CFG->enablegroupmembersonly) and $cm->groupmembersonly) {
3080 if ($groupingusers = groups_get_grouping_members($cm->groupingid, 'u.id', 'u.id')) {
3081 $users = array_intersect($users, array_keys($groupingusers));
3085 if (empty($users)) {
3089 $userlists = implode(',', $users);
3091 return $DB->count_records_sql("SELECT COUNT('x')
3092 FROM {assignment_submissions}
3093 WHERE assignment = ? AND
3094 timemodified > 0 AND
3095 userid IN ($userlists)", array($cm->instance));
3100 * Return all assignment submissions by ENROLLED students (even empty)
3102 * There are also assignment type methods get_submissions() wich in the default
3103 * implementation simply call this function.
3104 * @param $sort string optional field names for the ORDER BY in the sql query
3105 * @param $dir string optional specifying the sort direction, defaults to DESC
3106 * @return array The submission objects indexed by id
3108 function assignment_get_all_submissions($assignment, $sort="", $dir="DESC") {
3109 /// Return all assignment submissions by ENROLLED students (even empty)
3112 if ($sort == "lastname" or $sort == "firstname") {
3113 $sort = "u.$sort $dir";
3114 } else if (empty($sort)) {
3115 $sort = "a.timemodified DESC";
3117 $sort = "a.$sort $dir";
3120 /* not sure this is needed at all since assignmenet already has a course define, so this join?
3121 $select = "s.course = '$assignment->course' AND";
3122 if ($assignment->course == SITEID) {
3126 return $DB->get_records_sql("SELECT a.*
3127 FROM {assignment_submissions} a, {user} u
3128 WHERE u.id = a.userid
3129 AND a.assignment = ?
3130 ORDER BY $sort", array($assignment->id));
3135 * Add a get_coursemodule_info function in case any assignment type wants to add 'extra' information
3136 * for the course (see resource).
3138 * Given a course_module object, this function returns any "extra" information that may be needed
3139 * when printing this activity in a course listing. See get_array_of_activities() in course/lib.php.
3141 * @param $coursemodule object The coursemodule object (record).
3142 * @return object An object on information that the coures will know about (most noticeably, an icon).
3145 function assignment_get_coursemodule_info($coursemodule) {
3148 if (! $assignment = $DB->get_record('assignment', array('id'=>$coursemodule->instance), 'id, assignmenttype, name')) {
3152 $libfile = "$CFG->dirroot/mod/assignment/type/$assignment->assignmenttype/assignment.class.php";
3154 if (file_exists($libfile)) {
3155 require_once($libfile);
3156 $assignmentclass = "assignment_$assignment->assignmenttype";
3157 $ass = new $assignmentclass('staticonly');
3158 if ($result = $ass->get_coursemodule_info($coursemodule)) {
3161 $info = new object();
3162 $info->name = $assignment->name;
3167 debugging('Incorrect assignment type: '.$assignment->assignmenttype);
3174 /// OTHER GENERAL FUNCTIONS FOR ASSIGNMENTS ///////////////////////////////////////
3177 * Returns an array of installed assignment types indexed and sorted by name
3179 * @return array The index is the name of the assignment type, the value its full name from the language strings
3181 function assignment_types() {
3183 $names = get_plugin_list('assignment');
3184 foreach ($names as $name=>$dir) {
3185 $types[$name] = get_string('type'.$name, 'assignment');
3187 // ugly hack to support pluggable assignment type titles..
3188 if ($types[$name] == '[[type'.$name.']]') {
3189 $types[$name] = get_string('type'.$name, 'assignment_'.$name);
3196 function assignment_print_overview($courses, &$htmlarray) {
3197 global $USER, $CFG, $DB;
3199 if (empty($courses) || !is_array($courses) || count($courses) == 0) {
3203 if (!$assignments = get_all_instances_in_courses('assignment',$courses)) {
3207 $assignmentids = array();
3209 // Do assignment_base::isopen() here without loading the whole thing for speed
3210 foreach ($assignments as $key => $assignment) {
3212 if ($assignment->timedue) {
3213 if ($assignment->preventlate) {
3214 $isopen = ($assignment->timeavailable <= $time && $time <= $assignment->timedue);
3216 $isopen = ($assignment->timeavailable <= $time);
3219 if (empty($isopen) || empty($assignment->timedue)) {
3220 unset($assignments[$key]);
3222 $assignmentids[] = $assignment->id;
3226 if (empty($assignmentids)){
3227 // no assigments to look at - we're done
3231 $strduedate = get_string('duedate', 'assignment');
3232 $strduedateno = get_string('duedateno', 'assignment');
3233 $strgraded = get_string('graded', 'assignment');
3234 $strnotgradedyet = get_string('notgradedyet', 'assignment');
3235 $strnotsubmittedyet = get_string('notsubmittedyet', 'assignment');
3236 $strsubmitted = get_string('submitted', 'assignment');
3237 $strassignment = get_string('modulename', 'assignment');
3238 $strreviewed = get_string('reviewed','assignment');
3241 // NOTE: we do all possible database work here *outside* of the loop to ensure this scales
3243 list($sqlassignmentids, $assignmentidparams) = $DB->get_in_or_equal($assignmentids);
3245 // build up and array of unmarked submissions indexed by assigment id/ userid
3246 // for use where the user has grading rights on assigment
3247 $rs = $DB->get_recordset_sql("SELECT id, assignment, userid
3248 FROM {assignment_submissions}
3249 WHERE teacher = 0 AND timemarked = 0
3250 AND assignment $sqlassignmentids", $assignmentidparams);
3252 $unmarkedsubmissions = array();
3253 foreach ($rs as $rd) {
3254 $unmarkedsubmissions[$rd->assignment][$rd->userid] = $rd->id;
3259 // get all user submissions, indexed by assigment id
3260 $mysubmissions = $DB->get_records_sql("SELECT assignment, timemarked, teacher, grade
3261 FROM {assignment_submissions}
3262 WHERE userid = ? AND
3263 assignment $sqlassignmentids", array_merge(array($USER->id), $assignmentidparams));
3265 foreach ($assignments as $assignment) {
3266 $str = '<div class="assignment overview"><div class="name">'.$strassignment. ': '.
3267 '<a '.($assignment->visible ? '':' class="dimmed"').
3268 'title="'.$strassignment.'" href="'.$CFG->wwwroot.
3269 '/mod/assignment/view.php?id='.$assignment->coursemodule.'">'.
3270 $assignment->name.'</a></div>';
3271 if ($assignment->timedue) {
3272 $str .= '<div class="info">'.$strduedate.': '.userdate($assignment->timedue).'</div>';
3274 $str .= '<div class="info">'.$strduedateno.'</div>';
3276 $context = get_context_instance(CONTEXT_MODULE, $assignment->coursemodule);
3277 if (has_capability('mod/assignment:grade', $context)) {
3279 // count how many people can submit
3280 $submissions = 0; // init
3281 if ($students = get_enrolled_users($context, 'mod/assignment:submit', 0, 'u.id')) {
3282 foreach ($students as $student) {
3283 if (isset($unmarkedsubmissions[$assignment->id][$student->id])) {
3290 $link = new moodle_url('/mod/assignment/submissions.php', array('id'=>$assignment->coursemodule));
3291 $str .= '<div class="details"><a href="'.$link.'">'.get_string('submissionsnotgraded', 'assignment', $submissions).'</a></div>';
3294 $str .= '<div class="details">';
3295 if (isset($mysubmissions[$assignment->id])) {
3297 $submission = $mysubmissions[$assignment->id];
3299 if ($submission->teacher == 0 && $submission->timemarked == 0) {
3300 $str .= $strsubmitted . ', ' . $strnotgradedyet;
3301 } else if ($submission->grade <= 0) {
3302 $str .= $strsubmitted . ', ' . $strreviewed;
3304 $str .= $strsubmitted . ', ' . $strgraded;
3307 $str .= $strnotsubmittedyet . ' ' . assignment_display_lateness(time(), $assignment->timedue);
3312 if (empty($htmlarray[$assignment->course]['assignment'])) {
3313 $htmlarray[$assignment->course]['assignment'] = $str;
3315 $htmlarray[$assignment->course]['assignment'] .= $str;
3320 function assignment_display_lateness($timesubmitted, $timedue) {
3324 $time = $timedue - $timesubmitted;
3326 $timetext = get_string('late', 'assignment', format_time($time));
3327 return ' (<span class="late">'.$timetext.'</span>)';
3329 $timetext = get_string('early', 'assignment', format_time($time));
3330 return ' (<span class="early">'.$timetext.'</span>)';
3334 function assignment_get_view_actions() {
3335 return array('view');
3338 function assignment_get_post_actions() {
3339 return array('upload');
3342 function assignment_get_types() {
3346 $type = new object();
3347 $type->modclass = MOD_CLASS_ACTIVITY;
3348 $type->type = "assignment_group_start";
3349 $type->typestr = '--'.get_string('modulenameplural', 'assignment');
3352 $standardassignments = array('upload','online','uploadsingle','offline');
3353 foreach ($standardassignments as $assignmenttype) {
3354 $type = new object();
3355 $type->modclass = MOD_CLASS_ACTIVITY;
3356 $type->type = "assignment&type=$assignmenttype";
3357 $type->typestr = get_string("type$assignmenttype", 'assignment');
3361 /// Drop-in extra assignment types
3362 $assignmenttypes = get_list_of_plugins('mod/assignment/type');
3363 foreach ($assignmenttypes as $assignmenttype) {
3364 if (!empty($CFG->{'assignment_hide_'.$assignmenttype})) { // Not wanted
3367 if (!in_array($assignmenttype, $standardassignments)) {
3368 $type = new object();
3369 $type->modclass = MOD_CLASS_ACTIVITY;
3370 $type->type = "assignment&type=$assignmenttype";
3371 $type->typestr = get_string("type$assignmenttype", 'assignment_'.$assignmenttype);
3376 $type = new object();
3377 $type->modclass = MOD_CLASS_ACTIVITY;
3378 $type->type = "assignment_group_end";
3379 $type->typestr = '--';